Register Generic Type with Autofac

给你一囗甜甜゛ 提交于 2019-11-28 20:18:04

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();

The where T : Repository<O> generic constraint will take care of that the first argument should be an Repository<>

But it won't work with RegisterGeneric because it requires a generic interface so need to create a IUnitOfWork<T,O>

But your model is very strange. Why does your UnitOfWork need a Repository<> type argument?

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

}

Where IUnitOfWork<E>

public interface IUnitOfWork<E> : IDisposable where E : BaseEntity
{
    void SaveChanges();
}

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>>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!