【问题标题】:Autofac 4 with .NetCore API controller not loading带有.Net Core API控制器的Autofac 4未加载
【发布时间】:2017-10-13 01:29:34
【问题描述】:

我有一个实例,当我使用Autofac 时,我的控制器从未实例化。我想我在配置上做错了什么,但我无法弄清楚。我的解决方案中有 2 个项目。 1) API 2) 核心 所有模型、存储库和服务都存在于核心中。 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());
    }
}

Autofac 模块

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

【问题讨论】:

  • 不会是因为.Except&lt;IService&lt;IDataModel&gt;&gt;()的来电吧?如果您的 MemberDM 实现了 IDataModel 接口,那么就我所见,它不会被注册
  • 我尝试删除它,但它仍然不起作用。
  • 您的服务是通用的吗?泛型的.Name 返回TypeName`n,其中n 是泛型参数的数量。即MyService&lt;MemberDM&gt; 将返回MyService`1 作为名称,而不是MyService

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


【解决方案1】:

假设如下:

  • IService&lt;T&gt;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();

【讨论】:

  • 感谢这个。我喜欢你把它们结合起来的方式。我认为问题是我试图使用实际的接口而不是使用 .AsImplementedInterfaces()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-14
  • 2021-11-18
  • 1970-01-01
  • 2020-04-15
  • 2013-02-27
  • 1970-01-01
相关资源
最近更新 更多