Unity容器,解析单个对象

Vin*_*hak 5 c# unity-container

我开始了解Unity容器和依赖注入.我很难理解我的对象模型应该是什么样子.

在我的例子中,我创建了一个非常简单的Employee类(我省略了构造函数,因为这是我所困惑的):

public class Employee
{
    private int _id;
    private string _name;
    private DateTime _birthDate;

    public int Id
    {
        get { return _id; }
    }

    public string Name
    {
        get { return _name; }
    }

    public DateTime BirthDate
    {
        get { return _birthDate; }
    }
}
Run Code Online (Sandbox Code Playgroud)

此Employee对象应从数据库中获取其信息.这是一个填充数据库适配器,只是为了开发一个依赖:

public class DataAdapter
{
    public DbParameter NewParameter(string name, object value)
    {
        return new OracleParameter(name, value);
    }

    public DataRow ExecuteDataRow(string command, CommandType commandType, List<DbParameter> parameters)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add(new DataColumn("ID"));
        dt.Columns.Add(new DataColumn("NAME"));
        dt.Columns.Add(new DataColumn("BIRTH_DATE"));

        DataRow dr = dt.NewRow();

        dr["ID"] = new Random().Next();
        dr["NAME"] = "John Smith";
        dr["BIRTH_DATE"] = DateTime.Now;

        return dr;
    }
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,employee对象应采用"id"参数,以便知道从数据库中检索哪个Employee.假设我们使用的Employee构造函数如下所示:

public Employee(int id, DataAdapter dataAdapter)
{
    List<DbParameter> parameters = new List<DbParameter>();

    parameters.Add(dataAdapter.NewParameter("ID", id));

    DataRow dr = dataAdapter.ExecuteDataRow("GetEmployee", CommandType.StoredProcedure, parameters);

    if (dr == null)
        throw new EmployeeNotFoundException();

    _id = id;
    _name = Convert.ToString(dr["NAME"]);
    _birthDate = Convert.ToDateTime(dr["BIRTH_DATE"]);

    _id = employeeData.Id;
    _name = employeeData.Name;
    _birthDate = employeeData.BirthDate;
}
Run Code Online (Sandbox Code Playgroud)

除了使用ParameterOverride之外,我不确定如何使用Unity的解析器指定Employee的id:

class Program
{
    static void Main(string[] args)
    {
        UnityContainer container = new UnityContainer();

        container.RegisterType(typeof(EmployeeData));

        Employee emp = container.Resolve<Employee>(new ParameterOverride("id", 45));

        Console.WriteLine(emp.Id);
        Console.WriteLine(emp.Name);
        Console.WriteLine(emp.BirthDate);
        Console.ReadKey();
    }
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢这个,因为没有编译时检查以查看参数名称是否正确.这样的问题让我觉得我正在错误地应用这种模式.任何人都可以对我误解的内容有所了解吗?

谢谢!

jga*_*fin 6

依赖注入不适用于域模型/业务对象.它主要用于解析服务,即用于处理业务逻辑的类.

因此,您的人员通常使用存储库或任何其他数据访问模式加载.

所以:

  1. 您的数据访问类是使用DI注入的
  2. 您的数据访问类充当工厂并生成此人.

就像是

public class PersonRepository
{
    public PersonRepository(IDbConnection iGetInjected)
    {
    }

    public Person Get(int id)
    {
        // I create and return a person
        // using the connection to generate and execute a command
    }
}
Run Code Online (Sandbox Code Playgroud)