简体   繁体   English

AutoFac显式注册通用类型

[英]AutoFac register generic type explicitly

How do I tell register this generic repository? 我如何知道注册该通用存储库? Each request should pass ApplicationDbContext as TC . 每个请求都应将ApplicationDbContext作为TC传递。

I have tried something like this: 我已经尝试过这样的事情:

builder.RegisterGeneric(typeof(Repository<object, ApplicationDbContext>)).As(typeof(IRepository<>));

At the moment I have to register each one seperately which works but is tedious: 目前,我必须分别注册每个人,但可行,但很乏味:

builder.RegisterType<Repository<AudioModel, ApplicationDbContext>>().As<IRepository<AudioModel>>();

Repository: 仓库:

public class Repository<T, TC> : IRepository<T> 
        where T : class 
        where TC : DbContext
{
    private bool _disposed;

    protected TC Context { get; }

    public Repository()
    {

    }

    public Repository(TC context)
    {
        Context = context;
    }
}

Service: 服务:

public class UploadService : IUploadService
{
    private readonly IRepository<AudioModel> _repository;

    public UploadService(IRepository<AudioModel> repository)
    {
        _repository = repository;
    }
}

If TC should always be set to ApplicationDbContext , then it might be possible to make TC not a generic parameter (it doesn't need to be generic, it is always pretty specific). 如果TC应该始终设置为ApplicationDbContext ,则可以使TC不是通用参数(不需要通用,它总是非常特定的)。

If that is not an option, you could create a ApplicationDbContextRepository : 如果不是这样,则可以创建一个ApplicationDbContextRepository

public class ApplicationDbContext<T> : Repository<T, ApplicationDbContext>
{
}

and register this one as: 并将其注册为:

builder.RegisterGeneric(typeof(ApplicationDbContext<>)
       .As(typeof(IRepository<>));

But this depends on the rest of your application design. 但这取决于您的其余应用程序设计。

Try the following: 请尝试以下操作:

builder
    .RegisterGeneric(typeof(Repository<>)
    .As(typeof(IRepository<,>));

Autofac will register it correctly because the first type is the same in the implementation and the interface, and for the second type, it will simply pick any IRepository interface that has T as the first type and anything as the second. Autofac将正确注册它,因为第一种类型在实现和接口中是相同的,对于第二种类型,它将仅选择任何以T为第一类型并将第二种为第二类型的IRepository接口。

You can register your generic repository in this way: 您可以通过以下方式注册通用存储库:

builder.RegisterGeneric(typeof(Repository<>), typeof(IRepository<>));

You have to register to your AudioModel (I would use an interface instead object) and your db context. 您必须注册到AudioModel(我将使用接口代替对象)和数据库上下文。 Then you can resolve it. 然后您可以解决它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM