c# - 如何使用 IoC 容器在不同的地方使用不同的实现

标签 c# .net castle-windsor ioc-container

我想知道如何在不同的客户端中使用一个接口(interface)的不同实现。这是示例情况。

public interface IRandomIntGenerator
{
    int Generate();
}

public class SimpleRandomIntGenerator : IRandomIntGenerator
{
    public int Generate()
    {
        return new Random().Next();
    }
}

public class CryptoServiceProviderRandomIntGenerator : IRandomIntGenerator
{
    public int Generate()
    {
        var generator = new RNGCryptoServiceProvider();
        byte[] bytes = new byte[4];
        generator.GetBytes(bytes);
        return BitConverter.ToInt32(bytes, 0);
    }
}

然后我有两个不想了解特定实现的客户。一个生成登录代码,另一个选择数组中的随机项。

public class LogInCodeGenerator
{
    private readonly IRandomIntGenerator randomIntGenerator;

    public LogInCodeGenerator(IRandomIntGenerator randomIntGenerator)
    {
        this.randomIntGenerator = randomIntGenerator;
    }

    public string GenerateCode(int length)
    {
        var builder = new StringBuilder(length);
        for (int i = 0; i < length; i++)
            builder.Append(randomIntGenerator.Generate() % 10);
        return builder.ToString();
    }
}

public class RandomArrayItemChoose
{
    private readonly IRandomIntGenerator randomIntGenerator;

    public RandomArrayItemChoose(IRandomIntGenerator randomIntGenerator)
    {
        this.randomIntGenerator = randomIntGenerator;
    }

    public string Choose(string[] arr)
    {
        return arr[randomIntGenerator.Generate() % arr.Length];
    }
}

我想以这样的方式配置 IoC 容器,它将 SimpleRandomIntGenerator 用于 RandomArrayItemChooseCryptoServiceProviderRandomIntGenerator 用于 LogInCodeGenerator.

有没有办法用任何流行的 .NET IoC 容器来做到这一点?我对温莎城堡特别感兴趣。

最佳答案

使用 Windsor 的服务覆盖。请参阅 Windsor Docs 中的“为要使用的依赖项提供组件”部分.

关于c# - 如何使用 IoC 容器在不同的地方使用不同的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15136551/

相关文章:

c# - 为什么字符串数组的 "Count"Intellisensed 属性会变形为 "Length"?

c# - 在 C++ 中使用 C# 代码的可能方法有哪些

c# - 为什么 ViewComponentResult.ExecuteResult 方法返回 void?

c# - 使用内联逗号拆分逗号分隔的 csv 文件

c# - 使用 P/Invoked GlobalSize 时堆已损坏

c# - CaSTLe.Windsor - 为什么名称需要与界面相似?

c# - 如何使用 Simple Injector 注册命名实例

.net - 用于 .NET 的无锁和线程安全 IList<T>

c# - 如何将已解析的实例从控制反转传递给应用程序中的类?

asp.net - 尝试模拟依赖项并向 IoC 容器注册时出现 System.InvalidOperationException