我有 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
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 通用约束将负责第一个参数应该是 Repository
The where T : Repository<O> generic constraint will take care of that the first argument should be an Repository<>
但是它不适用于RegisterGeneric,因为它需要一个通用接口,所以需要创建一个IUnitOfWork...
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 构造函数中获得一个 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
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 注册部分封闭的泛型类型
发布评论