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

2021-6-21 anglehua

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 ?


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


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).



采集自互联网,如有侵权请联系本人

Powered by emlog 京ICP备15036472号-3 sitemap