C# 在c中用接口实例化类#

C# 在c中用接口实例化类#,c#,class,interface,instantiation,parameterized-constructor,C#,Class,Interface,Instantiation,Parameterized Constructor,嗨,这可能很琐碎,但我正试图理解使用接口的类实例化。下面是我的代码: public interface IRepository { string GetMemberDisplayName(); } public class Repository : IRepository { private readonly Manager _manager; public Repository() {} public Repository(string connectio

嗨,这可能很琐碎,但我正试图理解使用接口的类实例化。下面是我的代码:

public interface IRepository
{
    string GetMemberDisplayName();
}

public class Repository : IRepository
{
    private readonly Manager _manager;

    public Repository() {}

    public Repository(string connectionName)
    {
        _manager = new Manager(connectionName);
    }

    public string GetMemberDisplayName(string ID)
    {
        return "FooFoo";
    }
}
现在,在另一个使用repository类功能的类中,已将其实例化如下:

public class LogServiceHelper
{
    readonly IRepository _alrAttendance;
    readonly IRepository _alrUsers;

    public LogServiceHelper()
    {
        _alrAttendance = new Repository("value1");
        _alrUsers = new Repository("value2");
    }

    public string GetMemberName(string empId)
    {
        return _alrUsers.GetMemberDisplayName(empId);
    }
}

我的问题是,这是否是用参数化构造函数实例化类的正确方法。如果是的话,那么第二个问题是,为什么在这种情况下我们需要接口。我们可以直接实例化类而不创建接口?

是的,这就是调用参数化构造函数的方法,但不,这不是您应该做的

正如您所看到的,
logserviceheloper
Repository
类有着严格的依赖性,因此您是对的,接口不会给您带来任何好处。但是,如果注射:

你突然获得了抽象的好处。值得注意的是,单元测试可以通过假存储库,并且您可以切换到
IRepository
的另一个实现,而无需更改
logserviceheloper

接下来的问题是“谁创建了
存储库
具体类?”。为此,我建议您参考各种DI/IoC容器,如Autofac、Unity和NInject

我们可以直接实例化该类,而无需创建 接口

这的确是事实,它可能毫无问题地工作。但接下来我们要讨论的是关键问题:

  • 如果我的代码是可测试的,我将如何测试这段代码
  • 我是否可以在不更改LogServiceHelper的情况下轻松更改行为
如果您不依赖抽象,那么上述问题的答案很不幸是,。幸运的是,有一种叫做SOLID的东西,D代表


因此,通过这个简单的更改,您对模块进行了解耦,并且突然依赖于抽象,这为设计带来了很多好处。

接口就在那里,这样您就不会有新的具体实例,而是可以注入它们。现在您的构造函数没有参数化。这当然是好的,但不是最佳实践。你应该看看DI原理。
public LogServiceHelper(IRepository attendanceRepo, IRepository userRepo)
{
    _alrAttendance = attendanceRepo;
    _alrUsers = userRepo;
}
public LogServiceHelper(IRepository alrAttendance, IRepository alrUsers)
{
    _alrAttendance = alrAttendance;
    _alrUsers = alrUsers;
}