哇,不敢相信乔尔会喜欢这个:
var svc = new ShippingService(new ProductLocator(),
new PricingService(), new InventoryService(),
new TrackingRepository(new ConfigProvider()),
new Logger(new EmailLogger(new ConfigProvider())));
在此:
var svc = IoC.Resolve<IShippingService>();
许多人没有意识到您的依赖关系链可以嵌套,并且手动连接它们很快就会变得笨拙。即使有了工厂,重复代码也是不值得的。
是的,IoC 容器可能很复杂。但对于这个简单的例子,我已经证明它非常简单。
好吧,让我们进一步证明这一点。假设您有一些想要绑定到智能 UI 的实体或模型对象。这个智能 UI(我们称之为 Shindows Morms)希望您实现 INotifyPropertyChanged,以便它可以进行更改跟踪并相应地更新 UI。
“好吧,这听起来并不难”,所以你开始写作。
你从这个开始:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime CustomerSince { get; set; }
public string Status { get; set; }
}
..最终得到this:
public class UglyCustomer : INotifyPropertyChanged
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
string oldValue = _firstName;
_firstName = value;
if(oldValue != value)
OnPropertyChanged("FirstName");
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
string oldValue = _lastName;
_lastName = value;
if(oldValue != value)
OnPropertyChanged("LastName");
}
}
private DateTime _customerSince;
public DateTime CustomerSince
{
get { return _customerSince; }
set
{
DateTime oldValue = _customerSince;
_customerSince = value;
if(oldValue != value)
OnPropertyChanged("CustomerSince");
}
}
private string _status;
public string Status
{
get { return _status; }
set
{
string oldValue = _status;
_status = value;
if(oldValue != value)
OnPropertyChanged("Status");
}
}
protected virtual void OnPropertyChanged(string property)
{
var propertyChanged = PropertyChanged;
if(propertyChanged != null)
propertyChanged(this, new PropertyChangedEventArgs(property));
}
public event PropertyChangedEventHandler PropertyChanged;
}
这是令人厌恶的管道代码,我坚持认为,如果你手动编写这样的代码你从你的客户那里偷东西。有更好、更智能的工作方式。
你听说过这个词吗?“更聪明地工作,而不是更努力地工作”?
想象一下,您团队中的某个聪明人走过来说:“这是一个更简单的方法”
如果您将您的财产设为虚拟(冷静下来,这没什么大不了的),那么我们可以weave自动在该属性行为中。 (这称为 AOP,但不用担心名称,专注于它将为您做什么)
根据您使用的 IoC 工具,您可以执行如下操作:
var bindingFriendlyInstance = IoC.Resolve<Customer>(new NotifyPropertyChangedWrapper());
Poof!现在,所有手动 INotifyPropertyChanged BS 都会在相关对象的每个虚拟属性设置器上自动生成。
这是魔法吗?YES!如果您可以相信此代码能够完成其工作,那么您可以安全地跳过所有属性包装的繁琐内容。您有业务问题需要解决。
IoC 工具执行 AOP 的其他一些有趣用途:
- 声明式和嵌套数据库事务
- 声明式和嵌套工作单元
- Logging
- 前置/后置条件(按合同设计)