【问题标题】:How to inject dependency property using Ioc Unity如何使用 Ioc Unity 注入依赖属性
【发布时间】:2012-05-03 07:07:21
【问题描述】:

我有以下课程:

public interface IServiceA
{
    string MethodA1();
}

public interface IServiceB
{
    string MethodB1();
}

public class ServiceA : IServiceA
{
    public IServiceB serviceB;

    public string MethodA1()
    {
        return "MethodA1() " +serviceB.MethodB1();
    }
}

public class ServiceB : IServiceB
{
    public string MethodB1()
    {
        return "MethodB1() ";
    }
}

我使用 Unity 进行 IoC,我的注册如下所示:

container.RegisterType<IServiceA, ServiceA>(); 
container.RegisterType<IServiceB, ServiceB>(); 

当我解析ServiceA 实例时,serviceB 将是null。 我该如何解决这个问题?

【问题讨论】:

    标签: c# inversion-of-control unity-container ioc-container property-injection


    【解决方案1】:

    您至少有两个选择:

    你可以/应该使用构造函数注入,因为你需要一个构造函数:

    public class ServiceA : IServiceA
    {
        private IServiceB serviceB;
    
        public ServiceA(IServiceB serviceB)
        {
            this.serviceB = serviceB;
        }
    
        public string MethodA1()
        {
            return "MethodA1() " +serviceB.MethodB1();
        }
    }
    

    或者Unity支持属性注入,因为你需要一个属性和DependencyAttribute

    public class ServiceA : IServiceA
    {
        [Dependency]
        public IServiceB ServiceB { get; set; };
    
        public string MethodA1()
        {
            return "MethodA1() " +serviceB.MethodB1();
        }
    }
    

    MSDN 站点 What Does Unity Do? 是 Unity 的一个很好的起点。

    【讨论】:

    • 如果你可以在构造函数和属性注入之间进行选择,我认为你应该选择构造函数注入。属性注入将使类依赖于统一或一些其他调用者“记住”他们需要提供该依赖项。构造函数注入使任何尝试使用该类的人都清楚,依赖项对于该类是必不可少的。
    • 如果类有多个依赖项,在某些调用中不是全部都需要吗?它们都会被实例化吗?或者它们只会在访问时被实例化,如上: serviceB.method() ? @卡洛斯
    • @Legends 您的所有依赖项都将在创建 ServiceA 时被安装并注入,即使您没有在所有方法中使用它们。 Unity 不支持开箱即用的惰性实例化,但可以将其添加为扩展:pwlodek.blogspot.hu/2010/05/…
    • 我尝试了以下操作:container.RegisterType&lt;ICustomerDA, CustomerDA&gt;(); container.RegisterType&lt;ISampleBF, SampleBF&gt;(new InjectionProperty("CDA", container.Resolve&lt;ICustomerDA&gt;())); 我已将 SampleBF 中的属性 CDA 标记为依赖项。我的问题,如果我手动实例化 SampleBF 会起作用吗?因为我就是这样做的,当我尝试访问属性 CDA 时,总是得到“对象引用未设置为实例”。
    • 好的,我也必须统一解析调用类(在我的情况下是 ISampleBF),然后它就可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    相关资源
    最近更新 更多