我有UnitofWork类,它实现了IUnitOfWork.我尝试在Autofac上注册:
I have UnitofWork class and it implement IUnitOfWork. I try to register that with Autofac:
var builder = new ContainerBuilder(); builder .RegisterGeneric(typeof(UnitOfWork<Repository<>,>)) .As(typeof(IUnitOfWork)) .InstancePerDependency();实施是:
public class UnitOfWork<T, O> : IUnitOfWork where T : Repository<O> where O : BaseEntity { } public interface IUnitOfWork : IDisposable { void SaveChanges(); }给出错误预期类型"
但是这个可以在另一个项目上工作
but this one work on another project:
public class Repository<T> : GenericRepository<T> where T : BaseEntity { public Repository(IDbContext context) : base(context) { } } public abstract class GenericRepository<T> : IRepository<T>, IQueryable<T> where T : BaseEntity { } builder .RegisterGeneric(typeof(Repository<>)) .As(typeof(IRepository<>)) .InstancePerHttpRequest();推荐答案
您不能部分打开课程(例如,对于UnitOfWork<Repository<>,>,您已指定T,但未指定O)在typeof 内,尝试使用:
You cannot have partially opened classes (e.g. with UnitOfWork<Repository<>,> you have specified T but not O) inside a typeof, try it with:
var builder = new ContainerBuilder(); builder .RegisterGeneric(typeof(UnitOfWork<,>)) .As(typeof(IUnitOfWork)) .InstancePerDependency();where T : Repository<O>通用约束将确保第一个参数应为Repository<>
The where T : Repository<O> generic constraint will take care of that the first argument should be an Repository<>
但是它不适用于RegisterGeneric,因为它需要通用接口,因此需要创建IUnitOfWork<T,O>…
But it won't work with RegisterGeneric because it requires a generic interface so need to create a IUnitOfWork<T,O>…
但是您的模型非常奇怪.为什么您的UnitOfWork需要一个Repository<>类型的自变量?
But your model is very strange. Why does your UnitOfWork need a Repository<> type argument?
除了将其作为类型参数之外,您还可以在UnitOfWork<E>构造函数中获得一个Repository<>:
Instead of having it as a type argument you can get an Repository<> in your UnitOfWork<E> constructor:
public class UnitOfWork<E> : IUnitOfWork<E> where E : BaseEntity { private readonly Repository<E> repository; public UnitOfWork(Repository<E> repository) { this.repository = repository; } //.. other methods }IUnitOfWork<E>
public interface IUnitOfWork<E> : IDisposable where E : BaseEntity { void SaveChanges(); }以及Autofac注册:
And the Autofac registration:
var builder = new ContainerBuilder(); builder .RegisterGeneric(typeof(Repository<>)).AsSelf(); builder .RegisterGeneric(typeof(UnitOfWork<>)) .As(typeof(IUnitOfWork<>)) .InstancePerDependency(); var container = builder.Build(); // sample usage var u = container.Resolve<IUnitOfWork<MyEntity>>();更多推荐
向Autofac注册部分封闭的泛型类型
发布评论