带有.NetCore API控制器的Autofac 4无法加载

时间:2017-05-14 01:33:27

标签: c# dependency-injection asp.net-core autofac

我有一个实例,当我使用Autofac时,我的控制器永远不会被实例化。我认为我的配置有问题,但我无法弄清楚。我的解决方案中有2个项目。 1)API 2)核心所有模型,存储库和服务都存在于Core中。只有控制器在API中。

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

服务需要实例化的数据模型。在下面的实例中,MemberControllerMemberService<MemberDM>作为IService<IDataModel>。 我相信我已在AutofacModule中注册了所有内容,但它似乎没有工作,因为构造函数从未在MemberController中被命中。

非常感谢任何想法/帮助。

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

IServiceAssembly

 public interface IServiceAssembly
{
}

MemberController

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

1 个答案:

答案 0 :(得分:2)

假设如下:

  • IService<T>IDataModel实施IServiceAssembly
  • 以&#34; DM&#34;结尾的所有接口或&#34;服务&#34;在您的Core项目中有相应的实现。

然后它足以在您的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();