Register all the services at once using Default DI Container from ASP.NET 5 similar to Autofac

梦想的初衷 提交于 2020-01-03 14:28:08

问题


With ASP.NET 5, there's already a DI shipped as default and it looks interesting. I have been using Autofac with MVC 5 which has the option to register all the assembly at once. Here is a sample code that register all the classes that ends with "Service" in Autofac.

// Autofac Configuration for API
var builder = new ContainerBuilder();

builder.RegisterModule(new ServiceModule());

...
...

builder.RegisterAssemblyTypes(Assembly.Load("IMS.Service"))
                      .Where(t => t.Name.EndsWith("Service"))
                      .AsImplementedInterfaces()
                      .InstancePerLifetimeScope();

My question is, is there any thing similar to this in Default DI container from asp.net 5 where you can register all the services at once ?


回答1:


My question is, is there any thing similar to this in Default DI container from asp.net 5 where you can register all the services at once ?

Not OOTB, but Kristian Hellang created a cool package named Scrutor that adds assembly scanning capabilities to the built-in container. You can find it on NuGet.org.

services.Scan(scan => scan
    .FromAssemblyOf<ITransientService>()
        .AddClasses(classes => classes.AssignableTo<ITransientService>())
            .AsImplementedInterfaces()
            .WithTransientLifetime()
        .AddClasses(classes => classes.AssignableTo<IScopedService>())
            .As<IScopedService>()
            .WithScopedLifetime());



回答2:


You can still use the Autofac with Asp.net(5/Core) or MVC 6. You need to change the signature of ConfigureServices method to return IServiceProvider and argument as IServiceCollection.

E.g.

 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
     // We add MVC here instead of in ConfigureServices.
     services.AddMvc();

     // Create the Autofac container builder.
     var builder = new ContainerBuilder();

     // Add any Autofac modules or registrations.
     builder.RegisterModule(new AutofacModule());

     // Populate the services.
     builder.Populate(services);

     // Build the container.
     var container = builder.Build();

     // Resolve and return the service provider.
     return container.Resolve<IServiceProvider>();
 }

See more details here about integrating Autofac with Asp.net(5/Core).



来源:https://stackoverflow.com/questions/35490122/register-all-the-services-at-once-using-default-di-container-from-asp-net-5-simi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!