top of page
Writer's pictureKieran Foot

Generic Dependency Injection with using a Factory

Updated: Mar 7, 2023

In this post we will explore generic service creation using a factory. This way you can get the same functionality that ILogger has.


Have you ever wandered how ILogger always seems to have the type implementation that you want, well, it's simple... Generics.


So, below is how you would register a statically typed service into your DI container.

Services.RegisterSingleton<IService, Service>();

With IService being an interface and Service being a class that implements that interface.


But, what if the interface we want to register is generic?

Well, that's simple. For each generic service registration function, there is also a non generic alternative that takes arguments of Type.

Services.RegisterSingleton(typeof(IService), typeof(Service));

Then to make it generic, we just add empty <> to the type.

Services.RegisterSingleton(typeof(IService<>), typeof(Service<>));

Now, the type is registered inside the DI container without it's generic type information, meaning, when we request an IService<T>, we will get a generic class back. The class itself will be responsible for calling our factory and returning an implementation.


Let us see what an implementation of the generic interfaces and classes might look like.


// This interface is used for an actual service implementation.
public IService 
{
}

// This interface is used for registration in the DI container.
public interface IService<T> : IService
{
}

// This class is registered in the DI container and is responsible
// for creating service implementation using the factory.
public class Service<T> : IService<T>
{
    private readonly IService _internalImplementation;

    public Service(IServiceFactory factory)
    {
        _internalImplementation = factory.CreateService();
    }
}

// This interface represents a factory for IService<T>.
public interface IServiceFactory
{
    public IService CreateService();
}

// This class is a factory that creates the implementations of
// IService and returns them to the generic IService<T> 
// implementation.
public interface ServiceFactory : IServiceFactory
{
    
}

This is a work in progress...






41 views0 comments

Comments


bottom of page