Provides attribute based configuration of dependency injection services.
Microsoft's IServiceCollection
[AddToServices(Lifetime.Transient)] // This will register DefaultMath as self
[AddToServices(Lifetime.Transient, As = typeof(IMath))]
public class DefaultMath : IMath
{
public int Add(int x, int y)
{
return x + y;
}
}
using MR.AttributeDI.ServiceCollection;
services.ConfigureFromAttributes(typeof(Program).GetTypeInfo().Assembly); // Assemblies to search in
And then simply:
provider.GetService<IMath>();
provider.GetService<DefaultMath>():
[AddToServices(Lifetime.Transient, Tags = "foo")]
public class DefaultMath
...
Here, DefaultMath
won't be registered unless we specify its tag in configuration:
services.ConfigureFromAttributes(typeof(Program).GetTypeInfo().Assembly); // Will not register DefaultMath
services.ConfigureFromAttributes("foo", typeof(Program).GetTypeInfo().Assembly); // Will register DefaultMath
Multiple tags can be specified separated by a comma (for example "default, integration"
).
You can also forward service registrations for services where you want to share a single instance for multiple interfaces:
[AddToServices(Lifetime.Singleton, As = typeof(IFoo))]
[AddToServices(Lifetime.Singleton, As = typeof(IBar), ForwardTo = typeof(IFoo))]
public class SomeService : IFoo, IBar
{}