Covariance in Autofac?
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?
That is the expected behavior. However, you can take a look at the assembly scanning feature and the AsImplementedInterfaces method in particular.
精彩评论