Autofac 中的协方差?
我正在使用 AutoFAC 2.2.4,并且对容器解析中的协方差有疑问。
我的存储库有一个基本接口定义:
IRepository<T, TKey>
其中有 Find(Tkey)、FindAll() 等。
例如,它的使用方式如下:
IRepository<Catalog, int>
意味着 Catalog 有一个整数键。我像这样注册了它的存储库:
builder.RegisterType<CatalogRepository>()
.As<IRepository<Catalog, int>>();
一切都很好。 后来我意识到我需要一个额外的 .Find() 类型,所以我定义了一个新的接口:
ICatalogRepository : IRepository<Catalog, int>
{
Catalog Find(string name);
}
并且我更改了注册:
builder.RegisterType<CatalogRepository>()
.As<ICatalogRepository>();
但现在尝试解析 IRepository <目录,int>失败。我认为 Autofac 会识别与 ICatalogRepository 的关系并解决它。我必须这样做:
builder.RegisterType<CatalogRepository>()
.As<ICatalogRepository>()
.As<IRepository<Catalog, int>>();
让他们两个都得到解决。 (仍然存在从其他不知道派生接口的通用实体操作工具来解析 IRepository 的调用。)我做错了什么吗?
I am using AutoFAC 2.2.4 and have a question about covariance in container resolution.
I have a base interface definition for my repositories:
IRepository<T, TKey>
Which has Find(Tkey), FindAll(), etc.
It is used, for example, like this:
IRepository<Catalog, int>
meaning a Catalog has an integer key. I registered its repository like this:
builder.RegisterType<CatalogRepository>()
.As<IRepository<Catalog, int>>();
All was well.
Later on I realized I needed an additional type of .Find() so I defiend a new interface:
ICatalogRepository : IRepository<Catalog, int>
{
Catalog Find(string name);
}
And I changed the registeration:
builder.RegisterType<CatalogRepository>()
.As<ICatalogRepository>();
But now attempts to resolve IRepository < Catalog, int > fail. I thought Autofac would recognize the relationship to ICatalogRepository and resolve it. I have had to do this:
builder.RegisterType<CatalogRepository>()
.As<ICatalogRepository>()
.As<IRepository<Catalog, int>>();
To get them both to resolve. (There are still calls to resolve IRepository from other generic entity manipulation tools that are unaware of the derived interface.) Am I doing something wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是预期的行为。不过,您可以查看程序集扫描功能和 AsImplementedInterfaces 方法特别的。
That is the expected behavior. However, you can take a look at the assembly scanning feature and the AsImplementedInterfaces method in particular.