Unity 容器,解析单个对象
本文关键字:单个 对象 容器 Unity | 更新日期: 2023-09-27 17:57:23
我开始学习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; }
}
}
此 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;
}
}
理想情况下,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;
}
我不确定如何使用 Unity 的解析器指定员工的 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();
}
}
我不喜欢这样,因为没有编译时检查以查看参数名称是否正确。 像这样的问题让我觉得我应用了不正确的模式。 谁能说明一下我的误解?
谢谢!
依赖关系注入不适用于域模型/业务对象。它主要用于解析服务,即用于处理业务逻辑的类。
因此,您的人员通常使用存储库或任何其他数据访问模式进行加载。
所以:
- 数据访问类是使用 DI 注入 的
- 数据访问类充当工厂并生成人员。
类似的东西
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
}
}
您错误地使用此模式。DI 是关于注入依赖项,主要是通过接口。
您的代码应如下所示:
界面
public interface IEmployee
{
int Id { get; set;}
string name { get; set;}
DateTime BirthDate { get; set; }
}
和实施
public class Employee : IEmployee
{
public int Id { get; set;}
public string name { get; set;}
public DateTime BirthDate { get; set; }
}
然后,您可以通过以下方式解决依赖关系:
class Program
{
static void Main(string[] args)
{
UnityContainer container = new UnityContainer();
container.RegisterType(typeof(IEmployee), typeof(Employee));
IEmployee emp = container.Resolve<IEmployee>();
Console.ReadKey();
}
}
现在,您可以根据需要使用IEmployee接口的不同实现。