Skip to content

Step 1: Specifying Injection

Aaron Moore edited this page Jul 6, 2021 · 1 revision

Using the constructor on the InjectableAttribute you will be able to specify:

  • What class/interface is being injected
  • The service lifetime the injection lives for

and either:

  • The implementation being injected
  • The type acting as a factory for the injection

⚠️ If you provide both the implementation and a factory, the Factory will take precedence.

Example Attribute Usage

Specifying a concrete implementation as an interface, the following is the equivalent of coding services.AddScoped<IGreetingService, GreetingService>()

    public interface IGreetingService
    {
        public string Greet();
    }

    [Injectable(typeof(IGreetingService), typeof(GreetingService), ServiceLifetime.Scoped)]
    public class GreetingService : IGreetingService
    {
        public string Greet()
        {
            return $"{GetType().Name} was injected!";
        }
    }

If any parameter is left off, it uses the class it's attached to as an argument and ServiceLifetime.Scoped is the default service lifetime.

For example, the attribute usage above for GreetingService could be simplified to:

    [Injectable(typeof(IGreetingService))]
    public class GreetingService : IGreetingService

For example, the following is the same as services.AddScoped<MyClass>():

    [Injectable]
    public class MyClass

Property initializers can be used to set only a specific property. For example, the following is the same as services.AddSingleton<MyClass>():

    [Injectable(Lifetime = ServiceLifetime.Singleton)]
    public class MyClass

The Factory property can be used to specify a factory class that will be called for the implementation. The factory class provided must implement IInjectableFactory. For example, a factory attached to an injectable would look like:

    [Injectable(Factory = typeof(MyClassFactory))]
    public class MyClass
    {
        public MyClass(string someString)
        {
            //...
        }
    }

    public class MyClassFactory : IInjectableFactory
    {
        public object Create(IServiceProvider serviceProvider)
        {
            return new MyClass("I was injected via Factory!");
        }
    }

Note: If you specify the same factory type twice, it will NOT inject the same instance to both. It will create 2 instances.

Clone this wiki locally