Skip to content

Provides attribute based configuration of dependency injection services.

License

Notifications You must be signed in to change notification settings

mrahhal/MR.AttributeDI

Repository files navigation

MR.AttributeDI

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

About

Provides attribute based configuration of dependency injection services.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published