Register partically closed generic type with Autofac

前端 未结 1 422
灰色年华
灰色年华 2020-12-05 02:16

I have UnitofWork class and it implement IUnitOfWork. I try to register that with Autofac:

var builder = new ContainerBuilder();
bu         


        
1条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 03:11

    You cannot have partially opened classes (e.g. with UnitOfWork,> 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 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

    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 constructor:

    public class UnitOfWork : IUnitOfWork where E : BaseEntity
    {
        private readonly Repository repository;
    
        public UnitOfWork(Repository repository)
        {
            this.repository = repository;
        }
    
        //.. other methods
    
    }
    

    Where IUnitOfWork

    public interface IUnitOfWork : 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>();
    

    0 讨论(0)
提交回复
热议问题