简体   繁体   English

Autofac中具有通用类型参数的自动装配库

[英]Auto Wiring Repository With Generic Type Parameters in Autofac

I'm wondering if there's a convention-based approach for the registering the following in Autofac: 我想知道是否有一种基于约定的方法来在Autofac中注册以下内容:

builder.RegisterType<BatchDocumentRepository>()
    .As<IRepository<BatchDocument, IEnumerable<BatchDocument>, int>>();
builder.RegisterType<BatchRepository>()
    .As<IRepository<Batch, IEnumerable<Batch>, int>>();
builder.RegisterType<DeploymentReleaseRepository>()
    .As<IRepository<DeploymentRelease, IEnumerable<DeploymentRelease>, int>>();
builder.RegisterType<DeploymentRepository>()
    .As<IRepository<Deployment, IEnumerable<Deployment>, int>>();

The above works fine, but I'm just wondering if there's a cleaner and less repetitive way of doing it. 上面的方法工作正常,但我只是想知道是否有一种更干净且重复性更小的方法。 I had a look at this post: Resolving Generic Interface with Autofac , but it's not quite the same scenario. 我看了一下这篇文章: 使用Autofac解决通用接口 ,但是情况并不完全相同。

Thanks! 谢谢!

You could replace the .As<...>() with .AsImplementedInterfaces() . 您可以将.AsImplementedInterfaces() .As<...>()替换为.AsImplementedInterfaces() Beyond that, you could use: 除此之外,您可以使用:

builder.RegisterAssemblyTypes()
    .Where(t => t.GetInterfaces()
                 .Any(i => i.IsGenericType &&
                           i.GetGenericDefinition() == typeof(IRepository<>)))
    .AsImplementedInterfaces();

or something like that. 或类似的东西。

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

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