Search code examples
c#genericsdependency-injectionsimple-injector

Register generic types that have constructor arguments in Simple Injector


How to register generic types that have arguments in Simple Injector
(latest SimpleInjector version v3);

My interface is;

public interface IDbHelper<T> where T : class
{

    void SetInformation(string title, string description);
}

My class implementation;

public class JsonDbWrapper<T> : IDbHelper<T> where T : class
{
    private readonly JsonDb<T> _jsonFile;

    public JsonDbWrapper(string path, string filename, Encoding encoding)
    {
        _jsonFile = JsonDb<T>.GetInstance(path, filename, encoding);
    }


    public void SetInformation(string title, string description) { ... }
}

I tried following, ofcourse it's throwing an exception:

container.Register(typeof(IDbHelper<>), typeof(JsonDbWrapper<>));

Exception is;

Error: System.ArgumentException: The constructor of type JsonDbWrapper<T> contains parameter 'path' of type String which can not be used for constructor injection.

I can create a method to set path, filename and encoding. But I want them in constructor. I want to learn proper way of using Simple Injector.


Solution

  • if you want to register each helper with associate db class (e.g Person)

    the option is to register with delegate

    container.Register<IDbHelper<Person>>(() => new JsonDbWrapper<Person>("path","filename",Encoding.UTF8));
    var result = container.GetInstance<IDbHelper<Person>>();