In unity I can register all types of an interface from an assembly using this way.
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterTypes(
AllClasses.FromLoadedAssemblies().
Where(
type =>
typeof (IRunAtInit).IsAssignableFrom(type),
WithMappings.FromAllInterfaces,
WithName.TypeName);
}
Is it possible to implement it .net core like this way using its own default service container ?
We can add the service to the service container in the ConfigureServices method of the startup class. There are three different life options available: Transient, Scoped, and Singleton.
Singleton is a single instance for the lifetime of the application domain. Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET. Transient is a single instance per code request.
DependencyInjection. So, in the startup class, inside the ConfigureServices method, we need to add our dependency into the service collection which will dynamically inject whenever and wherever we want in the project. Also, we can mention which kind of instance we want to inject - the lifetime of our instance.
For registering the interface and classes, you need to go in the Program class (As Startup class is no more with . NET 6) and use these methods i.e "AddScoped" || "AddTransient" || "AddSingleton" as it defines the lifetime of the services. STEP 5 - Go to Program class and register it.
Try use Scrutor
extension: https://github.com/khellang/Scrutor
services.Scan(scan => scan
.FromAssemblyOf<IRunAtInit>()
.AddClasses(classes => classes.AssignableTo<IRunAtInit>())
.AsImplementedInterfaces()
.WithTransientLifetime());
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