繁体   English   中英

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

[英]Autofac 4 with .NetCore API controller not loading

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

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

该服务需要有关实例化的数据模型。 在下面的实例中, MemberControllerMemberService<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
  • Core项目中所有以“ DM”或“ Service”结尾的接口都有相应的实现。

然后,在您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM