.NET Core MVC项目中的Autofac属性注入

时间:2018-12-30 21:45:10

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

我有一个具有ILol类型属性和实现Lol的{​​{1}}类的控制器。

ILol

我尝试通过 Autofac 使用属性注入(属于我的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(); } } 类的一部分)

Startup

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

1 个答案:

答案 0 :(得分:0)

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

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