使用 Autofac 注册部分封闭的泛型类型 [英] Register partically closed generic type with Autofac
问题描述
我有 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
你在 typeof
中指定了 T
但没有指定 O
) ,试试:
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 注册部分封闭的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!