如何在依赖实现的类中使用类对象引用

时间:2018-02-15 20:14:13

标签: c# dependency-injection .net-core

我正在处理依赖注入并采用以下示例,如果我需要在服务中使用Customer类对象引用,这是实现IService类,这是最好的方法,考虑到客户对象总是会可以在服务类或抽象类中使用

public class Customer
{
    public int ID {get; set;}
    public string Name {get; set}

    public string dosomething(){}
}

public interface IService
{
    customer Serve(Guid RecordId);
}

public class Service : IService
{
    public void Serve()
    {
        Console.WriteLine("Need to create Customer Object here");

        Customer obj1 = new Customer();
        obj1.ID = 2;
        obj1.Name = "xyz";
    }
}

public class Client
{
    private IService _service;

    public Client(IService service)
    {
        this._service = service;
    }
}

2 个答案:

答案 0 :(得分:3)

让你的模型成为一个永远不需要依赖的“哑”数据容器(DTO)(或者说是抽象)。

public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
}

我们不是让Customer做某事,而是通过Customer提供服务。

public interface ISomething
{
    string DoSomething(Customer customer);
}

public class Something : ISomething
{
    public string DoSomething(Customer customer)
    {
        // Use customer to do something

        return "done";
    }
}

然后Service可以接受ISomething作为注入的依赖项并相应地处理Customer

public interface IService
{
    Customer Serve(Guid RecordId);
}

public class Service : IService
{
    private readonly ISomething something;

    public Service(ISomething something)
    {
        if (something == null)
            throw new ArgumentNullException(nameof(something));
        this.something = something;
    }

    public Customer Serve(Guid RecordId)
    {
        // No need to inject dependencies here
        Customer obj1 = new Customer();
        obj1.ID = 2;
        obj1.Name = "xyz";

        something.DoSomething(obj1);

        return obj1;
    }
}

答案 1 :(得分:0)

DTO或数据传输对象应仅包含属性。不应该有任何方法实现或抽象方法声明或任何东西。

DTO中可以有一个构造函数来初始化对象的成员。尝试一次查看SOLID原则。