Skip to content
This repository has been archived by the owner on Dec 9, 2020. It is now read-only.
Dávid Kaya edited this page Sep 11, 2017 · 9 revisions

Usage

Let's have following interface and class

public interface ICar {

}

public class Audi : ICar {

}

Lifetime

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.

Class Attributes

Class without interface

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 {

}

Single interface

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 {

}

Multiple interfaces

If your class implements multiple interfaces, you can specify which one should be registered

[RegisterTransient(typeof(IFuelConsumer)]
public class Audi : ICar, IFuelConsumer {

}

Factory method attributes

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

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(); 
}

Custom assembly resolver

To use custom assembly resolver you need to implement IAssemblyResolver interface and provide to the extension method.