Search code examples
dryioc

Open Generics with injected primitive


How can I register an Open Generic type with another open generic and primitive injected in the constructor?
See example below.
In this example, Resolve is throwing "Unable to resolve String as parameter "connectionString"" exception. (you can check live code here)

using System;
using DryIoc;

public class Program
{
    public static void Main()
    {
        var container = new Container();

        container.RegisterInstance("some_connection_string", serviceKey: "connectionString");
        container.Register(typeof(Configuration<>), Reuse.Singleton);
        container.Register(typeof (IEntityUpdater<>), typeof (SqlEntityUpdater<>), Reuse.Singleton);

        var p = container.Resolve<IEntityUpdater<EventArgs>>();

        Console.WriteLine(p);
    }   
}

public class Configuration<T> where T : class { }


internal interface IEntityUpdater<in T> where T : class
{
    void Update(T entity);
}

internal class SqlEntityUpdater<T> : IEntityUpdater<T> where T : class
{
    public SqlEntityUpdater(Configuration<T> configuration, string connectionString)
    {
    }

    public void Update(T entity) { }
}

Solution

  • First, RegisterInstance is depricated, use UseInstance.

    Second, the actual problem is that you registering instance with serviceKey and nowhere using this key for injection.

    So, you either remove the serviceKey parameter.

    Or, specify the key on injection side:

    container.Register(typeof(IEntityUpdater<>), typeof(SqlEntityUpdater<>), Reuse.Singleton,
        made: Parameters.Of.Type<string>(serviceKey: "connectionString"));