小编CDM*_*CDM的帖子

C#依赖容器和构造函数

我花了一些时间记录自己的依赖注入和IoC,但我还没有找到解决问题的方法.

我的问题涉及在使用依赖容器时对象的实例化,因为它创建了对构造函数的参数的依赖.在我遇到的几乎每个例子中,具体类的构造函数都没有任何参数.它使一切都变得"简单".因此我的问题在这里.

我们举一个例子:我需要从两个源A和B下载一些数据.源A包含各种格式的数据; 例如csv和xml.我们不需要为源B指定这样的东西.

这是一些代码(请注意我尽可能地简化代码来说明我的观点):

using System.Net;
using System.IO;
using System.Reflection;

namespace Question
{
  class Program
  {
    static void Main(string[] args)
    {
        //exemple of code using Client A
        DependencyContainer container1 = GetContainer1();
        IClient client1 = container1.Resolve<IClient>("xml");
        User user1 = new User(client1);
        user1.run();

        DependencyContainer container2 = GetContainer2();
        IClient client2 = container2.Resolve<IClient>();
        User user2 = new User(client2);
        user2.run();
    }

    public static DependencyContainer GetContainer1()
    {
        DependencyContainer container = new DependencyContainer();
        container.Register<IClient, ClientA>();
        return container;
    }

    public static DependencyContainer GetContainer2()
    {
        DependencyContainer container = …
Run Code Online (Sandbox Code Playgroud)

c# constructor dependency-injection ioc-container

4
推荐指数
1
解决办法
1537
查看次数