Register a generic type in unity based on a particular type

I am trying to emulate a behavior that I can customize in Ninject only using Unity.

I am trying to use a cached repository template, given the following classes and interface:

public interface IRepository<T>
{
    T Get();
}

public class SqlRepository<T> : IRepository<T>
    where T : new()
{
    public T Get()
    {
        Console.WriteLine("Getting object of type '{0}'!", typeof(T).Name);
        return new T();
    }
}

public class CachedRepository<T> : IRepository<T>
    where T : class
{
    private readonly IRepository<T> repository;

    public CachedRepository(IRepository<T> repository)
    {
        this.repository = repository;
    }

    private T cachedObject;
    public T Get()
    {
        if (cachedObject == null)
        {
            cachedObject = repository.Get();
        }
        else
        {
            Console.WriteLine("Using cached repository to fetch '{0}'!", typeof(T).Name);
        }
        return cachedObject;
    }
}

Basically, at any time when my application uses IRepository<T>, it should receive an instance CachedRepository<T>. But inside, CachedRepository<T>it should get the actual SQL repository SqlRepository<T>. In Ninject, I accomplished this using the following:

ninjectModule.Bind(typeof(IRepository<>)).To(tyepof(SqlRepository<>)).WhenInjectedExactlyInto(tyepof(CachedRepository<>));
ninjectModule.Bind(typeof(IRepository<>)).To(tyepof(CachedRepository<>));

In Oneness, how would I do the same? I have a version for non-shared repositories that works:

UnityContainer container = new UnityContainer();
container.RegisterType<IWidgetRepository, CachedWidgetRepository>(new InjectionMember[] { new InjectionConstructor(new SqlWidgetRepository()) });

But this syntax will not work at all with a common repository, as you cannot say new SqlRepository<>without a syntax error. Any ideas?

+4
1

, , :

container.RegisterType<IRepository<Things>, CachedRepository<Things>>(new InjectionMember[] {new InjectionConstructor(new SqlRepository<Things>())});

container.RegisterType<IRepository<OtherThings>, CachedRepository<OtherThings>>(new InjectionMember[] {new InjectionConstructor(new SqlRepository<OtherThings>())});

factory, : " factory".

// We will ask Unity to make one of these, so it has to resolve IRepository<Things>
public class UsesThings
{
    public readonly IRepository<Things> ThingsRepo;

    public UsesThings(IRepository<Things> thingsRepo)
    {
        this.ThingsRepo = thingsRepo;
    }
}


class Program
{
    static void Main(string[] args)
    {
        var container = new UnityContainer();

        // Define a custom injection factory.
        // It uses reflection to create an object based on the requested generic type.
        var cachedRepositoryFactory = new InjectionFactory((ctr, type, str) =>
            {
                var genericType = type.GenericTypeArguments[0];
                var sqlRepoType = typeof (SqlRepository<>).MakeGenericType(genericType);
                var sqlRepoInstance = Activator.CreateInstance(sqlRepoType);
                var cachedRepoType = Activator.CreateInstance(type, sqlRepoInstance);
                return cachedRepoType;
            });

        // Register our fancy reflection-loving function for IRepository<>
        container.RegisterType(typeof(IRepository<>), typeof(CachedRepository<>), new InjectionMember[] { cachedRepositoryFactory });

        // Now use Unity to resolve something
        var usesThings = container.Resolve<UsesThings>();
        usesThings.ThingsRepo.Get(); // "Getting object of type 'Things'!"
        usesThings.ThingsRepo.Get(); // "Using cached repository to fetch 'Things'!"
    }
}
+5

Source: https://habr.com/ru/post/1545708/


All Articles