【问题标题】:Autofac property injection in .NET Core MVC project.NET Core MVC 项目中的 Autofac 属性注入
【发布时间】:2019-05-27 15:28:55
【问题描述】:

我有一个带有ILol 类型属性和Lol 类实现ILol 的控制器。

public class UniversityController : Controller
{
    public ILol Lol { get; set; }

    public IActionResult Index()
    {
        ViewData["Header"] = "Hello, world!";
        ViewData["NullCheck"] = Lol == null ? "It's null" : Lol.GetLol();

        return View();
    }
}

我尝试以这种方式将 Property injectionAutofac 一起使用(我的 Startup 课程的一部分):

public IContainer ApplicationContainer { get; private set; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        // Dependency resolving.
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        ContainerBuilder builder = new ContainerBuilder();

        builder.RegisterType<Lol>().As<ILol>().PropertiesAutowired().InstancePerLifetimeScope();
        builder.Populate(services);

        IContainer container = builder.Build();

        ApplicationContainer = container;

        return new AutofacServiceProvider(container);
    }

它不起作用。该属性在运行时为空。虽然构造函数注入工作正常。

【问题讨论】:

    标签: asp.net-mvc asp.net-core dependency-injection .net-core autofac


    【解决方案1】:

    您必须指定需要在哪些控制器中使用属性注入:

     var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
                .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
     builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
    

    并调用 AddControllersAsServices():

    services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddControllersAsServices();

    如果您需要注册属性注入,只需在构建器中注册更多类型 PropertiesAutowired()。

    ConfigureServices 将如下所示:

    public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
    
            // Dependency resolving.
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddControllersAsServices();
    
            ContainerBuilder builder = new ContainerBuilder();
            builder.Populate(services);//Autofac.Extensions.DependencyInjection
    
            builder.RegisterType<Lol>().As<ILol>().PropertiesAutowired().InstancePerLifetimeScope();
            builder.Populate(services);
    
            var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
                .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
            builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
    
            IContainer container = builder.Build();
    
            ApplicationContainer = container;
    
            return new AutofacServiceProvider(container);
        }
    

    【讨论】:

    • @zergon321 在 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1) 上调用 AddControllersAsServices();还有我的例子github.com/svoychik/DotNetCore.AutofacExample
    • 您还需要确保在使用RegisterAssemblyTypes 注册控制器之前进行了builder.Populate(services) 调用。当您使用 AddControllersAsServices 时,服务将添加到 IServiceCollection 并调用 Populate 会将这些服务转换为 Autofac 注册。默认情况下,Autofac 将使用最后添加的注册作为默认值,并且您希望它是带有 PropertiesAutowired 的注册。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2018-10-12
    • 2020-11-24
    • 2019-03-18
    相关资源
    最近更新 更多