[英]Autofac 4 with .NetCore API controller not loading
我有一個實例,當我使用Autofac
時,永不實例化控制器。 我認為我在配置上做錯了什么,但我無法弄清楚。 我的解決方案中有2個項目。 1)API 2)核心所有模型,存儲庫和服務都位於核心中。 API中僅包含控制器。
如果我導航到默認或值控制器,則它們可以正常工作。 如果我從MemberController
刪除構造函數,它將可以使用,但是在服務上會得到NULL
引用。 如果我重新添加構造函數, MemberController
永遠不會加載(構造函數和get方法中的斷點)不會受到攻擊。
該服務需要有關實例化的數據模型。 在下面的實例中, MemberController
將MemberService<MemberDM>
用作IService<IDataModel>
。 我相信我已經在AutofacModule
注冊了所有內容,但似乎沒有用,因為從沒有在MemberController
使用構造函數。
任何想法/幫助將不勝感激。
啟動文件
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IContainer ApplicationContainer { get; private set; }
public IConfigurationRoot Configuration { get; private set; }
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add service and create Policy with options
services.AddCors(o => o.AddPolicy("CorsPolicy", p =>
{
p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
// Add framework services.
services.AddMvc();
var builder = new ContainerBuilder();
var connectionString = Configuration.GetValue<string>("DBConnection:ConnectionString");
builder.RegisterModule(new AutofacModule(connectionString));
builder.Populate(services);
ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors("CorsPolicy");
app.UseMvc();
appLifetime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose());
}
}
AutofacModule
public class AutofacModule :Autofac.Module
{
private string _connectionString;
public AutofacModule(string connectionString)
{
_connectionString = connectionString;
}
protected override void Load(ContainerBuilder builder)
{
// Register Connection class and expose IConnection
// by passing in the Database connection information
builder.RegisterType<Connection>() // concrete type
.As<IConnection>() // abstraction
.WithParameter("connectionString", _connectionString)
.InstancePerLifetimeScope();
// Register Repository class and expose IRepository
builder.RegisterType<Repository>() // concrete type
.As<IRepository>() // abstraction
.InstancePerLifetimeScope();
// Register DataModel as IDataModel
builder.RegisterAssemblyTypes(typeof(IServiceAssembly).GetTypeInfo().Assembly)
.Where(t => t.Name.EndsWith("DM"))
//.AsImplementedInterfaces();
.As<IDataModel>();
// Register Service Class as IService
builder.RegisterAssemblyTypes(typeof(IServiceAssembly).GetTypeInfo().Assembly)
.Where(t => t.Name.EndsWith("Service"))
.Except<IService<IDataModel>>()
//.AsImplementedInterfaces();
.As<IService<IDataModel>>();
}
}
IServiceAssembly
public interface IServiceAssembly
{
}
成員控制器
[Route("api/[controller]")]
public class MemberController : Controller
{
private readonly IService<MemberDM> _memberService;
public MemberController(IService<MemberDM> service)
{
_memberService = service;
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var result = await _memberService.Get(id);
return View(result);
}}
假設如下:
IService<T>
和IDataModel
實現IServiceAssembly
。 然后,在您的API項目中只有一個DI注冊聲明就足夠了。
// Register DataModel as IDataModel
// Register Service Class as IService
builder.RegisterAssemblyTypes(typeof(IServiceAssembly).GetTypeInfo().Assembly)
.Where(t => t.Name.EndsWith("DM") || t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.