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 ?
Autofac is a . Net-based IoC container. When classes interact with one another, it manages the dependencies between them that allow applications to remain flexible as they grow in size and complexity. Autofac is the most widely used DI/IoC container for ASP.NET, and it is fully compatible with.NET Core as well.
Using method "GetService" of the "HttpContext. RequestServices" property, we can get dependent services configured with the Service container. This is also known as property injection.
It might surprise you that most of what you need can be done in few lines without reliance on third-party packages!.. Once someone else has figured out what those few lines should be 😀
For example, here is a handful of concise DI extensions from Autofac and NetCore.AutoRegisterDi (all methods are annotated with source links). It lets you write registration logic like (example):
var types = typeof(BaseService<>).Assembly
.GetTypes()
.Where(t =>
!t.IsAbstract &&
t.IsClosedTypeOf(typeof(BaseService<>)))
).ToList();
services.RegisterAsImplementedInterfaces(types, ServiceLifetime.Scoped);
This blog post, .NET Core project without Autofac, has more examples and covers limitations if you want take one level further.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With