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?