c# - 如何基于同一个服务注册和解析多个组件

标签 c# dependency-injection inversion-of-control autofac

我有一个缓存的存储库,它实现了与真实存储库相同的接口(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/

相关文章:

java - I18N 属性上的 org.springframework.context.NoSuchMessageException

c# - MYSQL 空值干扰 C# 应用程序

c# - Regex.Replace 中的 MatchEvaluator 如何工作?

c# - 按两列分组 sql linq C#

php - PHP 全局常量是一种良好的现代开发实践吗?

c# - CaSTLe Windsor 按约定注册组件

c# - 如何在更高的类中使用覆盖的属性值?

c# - 如何在 C# 中通过表达式树构建集合过滤器

c# - Ninject 动态构造函数参数

java - Google Guice 中的计算常量