C# Unity2: Problem resolving genrics when using a lifetimemanager
-
28-09-2019 - |
Question
I am using ASP MVC 3 (RC) with Unity 2 with great success. However, I have one problem that I cannot wrap my head around. Behind the scenes I use POCO (Person, Company, ...) which I access through repositories. The repositories are made as generics (EFRepository), and use a context. Without LifetimeManager on the generic repository type everything works as expected:
var container = new UnityContainer();
container
.RegisterType<ObjectContext, DataLayerContext>(
new HttpRequestLifetimeManager<ObjectContext>())
.RegisterType(typeof(IRepository<>), typeof(EFRepository<>))
//Works
var unitOfWork = (IUnitOfWork)DependencyResolver.Current.GetService<IUnitOfWork>());
//Works
var webPersonRepository = (IRepository<WebPerson>)DependencyResolver.Current.GetService<IRepository<WebPerson>>();
However, when adding the LifetimeManager to the repository as well, the resolving fails:
var container = new UnityContainer();
container
.RegisterType<ObjectContext, DataLayerContext>(
new HttpRequestLifetimeManager<ObjectContext>())
.RegisterType(typeof(IRepository<>), typeof(EFRepository<>),
new HttpRequestLifetimeManager(typeof(IRepository<>)))
//Works
var unitOfWork = (IUnitOfWork)DependencyResolver.Current.GetService<IUnitOfWork>());
//Does NOT work anymore!
var webPersonRepository = (IRepository<WebPerson>)DependencyResolver.Current.GetService<IRepository<WebPerson>>();
Any ideas? The implementation of the HttpRequestLifetimeManager is very standard:
public class HttpRequestLifetimeManager<T> : HttpRequestLifetimeManager
{
public HttpRequestLifetimeManager() : base(typeof(T))
{
}
}
public class HttpRequestLifetimeManager : LifetimeManager, IDisposable
{
private readonly string _key;
public HttpRequestLifetimeManager(Type T)
{
_key = @"HttpRequestContextLifetimeManager" + T.Name;
}
public override object GetValue()
{
return HttpContext.Current.Items[_key];
}
public override void RemoveValue()
{
HttpContext.Current.Items.Remove(_key);
}
public override void SetValue(object newValue)
{
HttpContext.Current.Items[_key] = newValue;
}
public void Dispose()
{
RemoveValue();
}
}
Any help would be greatly appreciated!
Thanks! /Victor
Solution
If anyone wants to know, the reason was that the custom LifetimeManager I used used a type as input (either using generics or as a constructor argument). When using the LifetimeManager on a generic type that will fail, so dont do that :)
In the end we decided to use {string}+Guid.NewGuid() as the key.
/Victor