如何基于同一个服务注册和解析多个组件
How to register and resolve multiple components based on same service
我有一个缓存的存储库,它实现了与真实存储库相同的接口。即
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)
{
}
}
您可以为此使用密钥服务: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)
{
}
}
或者创建一个 Module
,它将根据条件自动添加参数,例如,如果服务实现了某个接口。
我有一个缓存的存储库,它实现了与真实存储库相同的接口。即
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)
{
}
}
您可以为此使用密钥服务: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)
{
}
}
或者创建一个 Module
,它将根据条件自动添加参数,例如,如果服务实现了某个接口。