为什么使用Builddup和Unity进行DI

时间:2014-06-24 01:28:51

标签: c# dependency-injection unity-container

我正在尝试解决为什么/何时使用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);

看起来很简单。所以:

  1. BuildUp只是一种语法糖的形式,如果我有多种属性来解析类型,那么我可以使用一行代码来实现它,而不是每个属性解析一次?
  2. 我是否必须将Dependency属性放在我要构建的每个属性上?
  3. 我可以在BuildUp中使用命名注册吗?
  4. 使用Buildup有什么其他好处?

0 个答案:

没有答案