Autofac 4 与 .NetCore API 控制器未加载



我有一个实例,当我使用Autofac时,我的控制器永远不会实例化。 我想我在配置上做错了什么,但我无法弄清楚。 我的解决方案中有 2 个项目。 1) API 2) 核心 所有模型、存储库和服务都位于核心中。 API 中只有控制器。

如果我导航到默认值或值控制器,它们工作正常。如果我从MemberController中删除构造函数,它将起作用,但我得到NULL服务引用。 如果我重新添加构造函数,则永远不会命中MemberController(构造函数和 get 方法中的断点)。

该服务在实例化时需要一个数据模型。 在下面的实例中,MemberControllerMemberService<MemberDM>作为IService<IDataModel>。 我相信我已经在我的AutofacModule中注册了所有内容,但它似乎不起作用,因为构造函数永远不会被击中MemberController.

任何想法/帮助将不胜感激。

启动.cs

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>>();
}
}

服务大会

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.
  • 核心项目中所有以"DM"或"服务"结尾的接口都有相应的实现。

然后,在 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();

最新更新