我正在尝试解决为什么/何时使用Unity容器的BuildUp方法。如果我有以下内容:
[TestInitialize]
public void SetupEnvironment()
{
var container = new UnityContainer();
container.RegisterType<ILocalizingKeyHolder, FeeTypeKeyHolder>(
typeof(FeeType).Name);
var keyHolderFactory = new UnityLocalizingKeyHolderFactory(container);
var ctx = new TspDbContext(keyHolderFactory);
...
}
当我通过EF实现对象时,我调用了DAL中的keyHolderFactory:
public override void OnObjectMaterialized(object entity)
{
var localizableEntity = (entity as ILocalizableEntity);
if (localizableEntity != null)
{
this.KeyHolderFactory.AttachKeyHolder(localizableEntity);
}
}
keyHolderFactory实现如下:
public class UnityLocalizingKeyHolderFactory : ILocalizingKeyHolderFactory
{
private UnityContainer Container { get; set; }
public UnityLocalizingKeyHolderFactory(UnityContainer container)
{
this.Container = container;
}
public void AttachKeyHolder(ILocalizableEntity localizableEntity)
{
localizableEntity.KeyHolder = Container.Resolve<ILocalizingKeyHolder>(
localizableEntity.GetType().Name);
localizableEntity.UpdateLocalizingKey();
}
}
我实际上看不到使用BuildUp将LocalizingKeyHolder注入实体有什么好处?
此
localizableEntity.KeyHolder =
Container.Resolve<ILocalizingKeyHolder>(localizableEntity.GetType().Name);
看起来很简单。所以: