.NET Core IOC RegisterAssemblyTypes Equivalant

lee*_*n3o 12 asp.net autofac asp.net-core-mvc asp.net-core

我正在使用.NET核心IOC内置的标准.但我需要一些像AutoFac一样的功能.我希望/需要限制此项目中第三方依赖项的数量.所以希望我能在标准.NET Core IOC中使用类似于AutoFac方法的东西.

builder.RegisterAssemblyTypes(assemblyhere).AsImplementedInterfaces();
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Pie*_*sso 8

是的,您可以使用内置的.NET Core IOC容器,使用Scrutor扩展方法.它有一些很好的装配扫描功能.

试试这个:

services.Scan(scan => scan
                .FromAssemblies(typeof(yourassembly).GetTypeInfo().Assembly)
                .AddClasses()
                .AsImplementedInterfaces()
                .WithScopedLifetime());
Run Code Online (Sandbox Code Playgroud)

它适用于内置的IOC容器,虽然它本身不是内置包(Nuget上的Scrutor包):


ssm*_*ith 0

您可以实现自己的扩展方法来执行此类操作,但如果 Autofac 有您想要的功能,您也可以简单地使用它。你有什么理由可以这么做吗?为此,您只需配置它并从 中返回它ConfigureServices,如下所示

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    // Add other framework services

    // Add Autofac
    var containerBuilder = new ContainerBuilder();
    containerBuilder.RegisterModule<DefaultModule>();
    containerBuilder.Populate(services);
    var container = containerBuilder.Build();
    return new AutofacServiceProvider(container);
}
Run Code Online (Sandbox Code Playgroud)