Hooking Generic Repository With IOC container
I am trying to create a generic repository pattern where i can swtich ORM technogies , But i stumbled upon this problem when trying to hook with IOC container
public interface IRepository<T>
{
//members
}
For NHbernate this works fine
public class FNHRepository<T>: IRepository<T>
{ //members }
But for Entity i am forced to add where clause
public class EFRepository<T> : IRepository<T> where T : class
{
if i am omiting the "where clause" i am not able to do
dbset = DataContext.Set<T>() ;
saying only reference type can be used as T
The problem comes when i am trying to hook IRepository with an IOC , like this
.RegisterType(typeof(IRepository<>), typeof(EFRepository<>));
I am not able to hook the interface if the implemeting class is having where T : class 开发者_运维技巧, I am getting the following execption
xception is: InvalidOperationException - The current type, System.Web.Mvc.IControllerFactory, is an interface and cannot be constructed. Are you missing a type mapping?
Any help appriciated , i tried this with Unity and Autofac and getting the same error
Not sure about Unity, but you should be able to register a generic class with constraints just fine.
builder.RegisterGeneric(typeof(EFRepo...))
.AsImplementedInterfaces();
The problem though is this: without the same constraint on the interface, this is bound to fail:
container.Resolve<IRepo<int>>();
精彩评论