-
Notifications
You must be signed in to change notification settings - Fork 2
Usage
Let's have following interface and class
public interface ICar {
}
public class Audi : ICar {
}
Lifetimes are inherited from Microsoft's documentation
Lifetime type | Description |
---|---|
Transient | Transient lifetime services are created each time they are requested. |
Scoped | Scoped lifetime services are created once per request. |
Singleton | Singleton lifetime services are created the first time they are requested and then every subsequent request will use the same instance. |
Attributes are in Register[Lifetime type]
or Register[Lifetime type]Factory
form.
If you want to add a class which does not implement any interface, you can do it as you would with class that implements an interface
[RegisterTransient]
public class Mercedes {
}
If you want to add Audi
as an implementation of ICar
into IServiceCollection
you just need to add RegisterTransient
, RegisterScoped
or RegisterSingleton
attribute like
[RegisterTransient]
public class Audi : ICar {
}
If your class implements multiple interfaces, you can specify which one should be registered
[RegisterTransient(typeof(IFuelConsumer)]
public class Audi : ICar, IFuelConsumer {
}
If you want to add Audi
as an implementation of ICar
using static factory method, you can do following
[RegisterTransientFactory(typeof(ICar))]
public static Audi CreateAudi(IServiceProvider provider) {
return new Audi();
}
Registration is done using one of the extension methods
Extension method | Description |
---|---|
public static IServiceCollection AutoRegister(this IServiceCollection services) |
Dependify scans all assemblies for the registration attributes. |
public static IServiceCollection AutoRegister(this IServiceCollection services, params Assembly[] assemblies) |
Dependify scans specified assemblies for the registration attributes. |
public static IServiceCollection AutoRegister(this IServiceCollection services, string @namespace) |
Dependify scans all assemblies for the registration attributes in the specified namespace. |
public static IServiceCollection AutoRegister(this IServiceCollection services, IAssemblyResolver assemblyResolver) |
Dependify scans assemblies resolved from assemblyResolver . |
To register all classes or factory methods call one of the AutoRegister(...)
methods.
For example to register all class and factory methods marked with registration attributes call
public void ConfigureServices(IServiceCollection services) {
services.AutoRegister();
}
To use custom assembly resolver you need to implement IAssemblyResolver
interface and provide to the extension method.