/MR.AttributeDI

Provides attribute based configuration of dependency injection services.

Primary LanguageC#MIT LicenseMIT

MR.AttributeDI

Build status NuGet version License

Provides attribute based configuration of dependency injection services.

CHANGELOG

Supported containers

MR.AttributeDI.ServiceCollection NuGet version

Microsoft's IServiceCollection

MR.AttributeDI.Autofac NuGet version

Autofac

Example using 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>():

Using tags

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

Forwarding

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
{}