Dependency Injection
Do you hate having to update several areas of code, just to install a dependency? Is DI hard for installing against multiple interfaces or open generics? If so, this library is for you! It uses source generation to create a single file that contains all of your dependency injection registrations. This means you can just add the attribute and it will generate the code for you.
Features
Section titled “Features”- Source generate all attributed classes to a single add file - saves you the boilerplate
- Extension methods for registering a dependency against multiple interfaces
- Extension methods for startup tasks (different to hosted services that don’t work on mobile)
- Supports multiple interfaces
- Supports open generics
- Supports keyed services
The Results
Section titled “The Results”THIS:
using Microsoft.Extensions.DependencyInjection;using Shiny.Extensions.DependencyInjection;
// given the following code from a usernamespace Sample{ public interface IStandardInterface;
public interface IStandardInterface2;
[Service(ServiceLifetime.Singleton)] public class ImplementationOnly;
[Service(ServiceLifetime.Transient, "ImplOnly")] public class KeyedImplementationOnly;
[Service(ServiceLifetime.Singleton)] public class StandardImplementation : IStandardInterface;
[Service(ServiceLifetime.Scoped, "Standard")] public class KeyedStandardImplementation : IStandardInterface;
[Service(ServiceLifetime.Singleton)] public class MultipleImplementation : IStandardInterface, IStandardInterface2;
[Service(ServiceLifetime.Scoped)] public class ScopedMultipleImplementation : IStandardInterface, IStandardInterface2;
[Service(ServiceLifetime.Scoped, "KeyedGeneric")] public class TestGeneric<T1, T2> { public T1 Value1 { get; set; } public T2 Value2 { get; set; } }}
GENERATES THIS:
// <auto-generated />using global::Microsoft.Extensions.DependencyInjection;using global::Shiny.Extensions.DependencyInjection;
namespace Sample{ public static class __GeneratedRegistrations { public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddGeneratedServices( this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services ) { services.AddSingleton<global::Sample.ImplementationOnly>(); services.AddKeyedTransient<global::Sample.KeyedImplementationOnly>("ImplOnly"); services.AddSingleton<global::Sample.IStandardInterface, global::Sample.StandardImplementation>(); services.AddKeyedScoped<global::Sample.IStandardInterface, global::Sample.KeyedStandardImplementation>("Standard"); services.AddSingletonAsImplementedInterfaces<global::Sample.MultipleImplementation>(); services.AddScopedAsImplementedInterfaces<global::Sample.ScopedMultipleImplementation>(); services.AddKeyedScoped(typeof(global::Sample.TestGeneric<,>), "KeyedGeneric");
return services; } }}