【问题标题】:Autofac: injecting in injected object (resolve difficult dependencies)Autofac:注入注入对象(解决困难的依赖关系)
【发布时间】:2013-06-26 13:21:11
【问题描述】:

我需要将对象 B 和 C 注入到 A 中,其中 B 使用对象 C(所有对象都在 A​​utofac 中创建)如果 B 不需要使用 C(对象 C 用于存储参数)并且我可以使用硬编码值我可以这样写:

     builder.RegisterType<B>().As<IB>().WithParameter("key","value");

但是如果参数是通过autofac创建的怎么办?

     builder.RegisterType<B>().As<IB>().WithParameter("key",C.value);

【问题讨论】:

    标签: c# ioc-container autofac


    【解决方案1】:

    我相信这就是你要找的东西

    class B
    {
        public B(string key, C anotherDependency)
        {
            this.Key = key;
        }
    
        public string Key { get; private set; }
    }
    
    class C
    {
        public string Value { get { return "C.Value"; } }
    }
    
    [TestMethod]
    public void test()
    {
        var cb = new ContainerBuilder();
    
        cb.RegisterType<B>().WithParameter(
            (prop, context) => prop.Name == "key",
            (prop, context) => context.Resolve<C>().Value);
    
        cb.RegisterType<C>();
    
        var b = cb.Build().Resolve<B>();
        Assert.AreEqual("C.Value", b.Key);
    }
    

    您可能要考虑的另一种方式是这样

    class B
    {
        public B(string key) { ... }
    
        public B(C c) : this(c.Value) { }
    }
    

    这意味着您不需要在组合根中添加任何特殊内容 - Autofac 将自动选择第二个构造函数(假设已注册 C 而未注册 string)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-31
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多