我有一个缓存的存储库,它实现了与真实存储库相同的接口(interface)。即
public class CachedLocationRepository : ILocationRepository
public class LocationRepository : ILocationRepository
如何向 Autofac
注册两者并告诉特定服务使用哪个组件?
即一些组件使用真实版本,一些使用缓存版本。
public class UseRealImpl : IUseRealImpl
{
public UseRealImpl(ILocationRepository locationRepository)
{
}
}
public class UseCachedImpl : IUseCachedImpl
{
public UseCachedImpl(ILocationRepository cachedLocationRepository)
{
}
}
最佳答案
您可以为此使用 key 服务:Named and Keyed Services
例如:
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<CachedLocationRepository>()
.As<ILocationRepository>()
.Keyed<ILocationRepository>(RepositoryType.Cached);
builder.RegisterType<LocationRepository>()
.As<ILocationRepository>()
.Keyed<ILocationRepository>(RepositoryType.Real);
然后您可以使用参数注册 UseCachedImpl
:
builder.RegisterType<UseCachedImpl>()
.As<UseCachedImpl>()
.WithParameter((pi, c) => pi.ParameterType == typeof(ILocationRepository)
,(pi, c) => c.ResolveKeyed<ILocationRepository>(RepositoryType.Cached));
或者使用WithKeyAttribute
public class UseCachedImpl
{
public UseCachedImpl([WithKey(RepositoryType.Cached)]ILocationRepository cachedLocationRepository)
{
}
}
或者创建一个模块
,它将根据条件自动添加参数,例如,如果服务实现了某个接口(interface)。
关于c# - 如何基于同一个服务注册和解析多个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29108813/