使用没有接口的Ninject进行依赖注入



我们正在开发一个Mvc应用程序,我们希望在其中使用nject使用依赖项注入。目前,我们在不同的类库"ShopEntities"中维护实体,在我们的mvc应用程序中,我们使用这些实体。让我们考虑ShopEntity中的一个类。

namespace ShopEntities
{
public class Customers
{
public int custId {get;set;}
public string custName {get;set;}
public string Address {get;set;}
public string ShippingAddress {get;set;}
}
}

现在,当我们想在mvc应用程序中使用它时,我们创建一个实例并设置如下属性,

public ActionResult Index()
{
ShopEntities.Customers cust = new ShopEntities.Customers();
cust.CustName = "Sam";
cust.IAddress = "xyz";
cust.ShippingAddress = "xyz xyx xyz"; 
}

如何在此处使用Inject以避免依赖关系?此外,我们不想创建接口,因为这在范围上是有限的。提前谢谢。

从表示层抽象出Customer实体的使用的方法不是将实体本身隐藏在某种ICustomer后面,也不是让DI容器构建它。将数据对象隐藏在接口后面通常没有用处;接口旨在抽象行为,而不是数据。

正如NightOwl已经指出的,您的Customer实体是运行时数据,您应该而不是使用容器来构建包含运行时数据的对象图。

相反,您应该将特定的业务操作隐藏在抽象后面。这种抽象可以由表示层使用,也可以由业务层实现。例如:

public interface ICustomerServices
{
void CreateCustomer(string customerName, string homeAddress, 
string shippingAddress);
void ChangeShippingAddress(Guid customerId, string shippingAddress);
}

您的控制器可以依赖于这个抽象:

private readonly ICustomerServices customerServices;
public CustomerController(ICustomerServices customerServices) {
this.customerServices = customerServices;
}
public ActionResult Index()
{
this.customerServices.CreateCustomer("Sam", "xyz", "xyz xyz xyz");
}

现在,您的业务层可以为这个抽象创建一个内部使用实体的实现:

public class CustomerServices : ICustomerServices
{
private readonly EntitiesContext context;
public CustomerServices(EntitiesContext context) {
this.context = context;
}
public void CreateCustomer(string customerName, string homeAddress,
string shippingAddress)
{
// NOTE that I renamed 'Customers' to 'Customer', since it holds information
// to only one customer. 'Customers' implies a collection.
Customer cust = new ShopEntities.Customer();
cust.CustName = "Sam";
cust.IAddress = "xyz";
cust.ShippingAddress = "xyz xyx xyz"; 
this.context.Customers.Add(cust);
this.context.SubmitChanges();
}
public void ChangeShippingAddress(...) { ... }
}

这样做的优点是可以保持表示层较薄,但与其他方法相比,所示方法仍有一些不足之处。其中一种替代方案是在SOLID设计中使用基于消息的方法,如本文所述。

如果我理解你的问题,你应该创建中间业务层,将ShopEntities转换为你自己的实体:

namespace MyShopEntities
{
public class MyCustomers
{
public int custId {get;set;}
public string custName {get;set;}
public string Address {get;set;}
public string ShippingAddress {get;set;}
}
}
public ActionResult Index()
{
ShopEntities.Customers cust = new MyShopEntities.MyCustomers();
cust.CustName = "Sam";
cust.IAddress = "xyz";
cust.ShippingAddress = "xyz xyx xyz"; 
}
class BussinesModel
{
void Insert(ShopEntities.Customer customer)
{
// use ShopEntities.Customer only in wrapper
// if you later switch to another Customer dependency,
// you just change this     wrapper
MyShopEntities.MyCustomers cust = new MyShopEntities.MyCustomers();
cust.CustName = customer.CustName;
cust.IAddress = customerIAddress;
cust.ShippingAddress = customer.ShippingAddress; 
InsertInternal(cust);
}
void InsertInternal(MyShopEntities.MyCustomer customer)
{
// use MyCustomer for all your bussines logic
}
}

最新更新