-
Notifications
You must be signed in to change notification settings - Fork 1
Step 1: Specifying Injection
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
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 : IGreetingServiceFor example, the following is the same as services.AddScoped<MyClass>():
[Injectable]
public class MyClassProperty 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 MyClassThe 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.