【问题标题】:Unity container, resolve to an abstract class level and not top InterfaceUnity 容器,解析为抽象类级别而不是顶级接口
【发布时间】:2014-11-19 04:52:06
【问题描述】:

我根据层次结构定义了以下代码 -

public interface ISomeInterface
    {
        bool DoSomething();
    }

    public abstract class AbsActualWorker : ISomeInterface
    {
        public bool DoSomething()
        {
            Console.WriteLine("DoSomething");
            throw new Exception("throwing exception for the sake of it!");
        }

        public abstract bool DoSomething2();
    }

    public class ActualWorker : AbsActualWorker
    {
        public override bool DoSomething2()
        {
            Console.WriteLine("DoSomething2");
            Thread.Sleep(1000);
            return true;
            //throw new Exception("throwing exception for the sake of it!");
        }
    }

我正在尝试解析到ActualWorker 级别并执行其DoSomething2

var container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<AbsActualWorker, ActualWorker>();
container
            .RegisterType<ISomeInterface, ActualWorker>(new Interceptor(new InterfaceInterceptor()),
                                                                            new InterceptionBehavior(new MyLoggerBehavior())
                                                           );
var instance = container.Resolve<ISomeInterface>();
if (instance != null)
{
    instance.DoSomething();
}

代码愉快地解析,可以调用

instance.DoSomething();

当我将实例转换为 ActualWorker 时,我得到了空值。我想拨打电话DoSomething2

public class MyLoggerBehavior : IInterceptionBehavior
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var returnValue = getNext()(input, getNext);

            if (returnValue.Exception != null)
            {
                Console.WriteLine("Exception occurred!!");
            }
            else
            {
                Console.WriteLine("Method {0} returned {1}", input.MethodBase, returnValue.ReturnValue);
            }
            return returnValue;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public bool WillExecute
        {
            get { return true; }
        }
    }

【问题讨论】:

    标签: c# .net unity-container


    【解决方案1】:

    您的问题出在拦截器上。由于

    container.RegisterType<ISomeInterface, ActualWorker>(new Interceptor(new InterfaceInterceptor()), new InterceptionBehavior(new MyLoggerBehavior()));
    

    你得到的 ISomeInterface 不是 ActualWorker 类型,而是实现 ISomeInterface 的 wrappertype。此类型无法强制转换为 ActualWorker。

    如果您使用依赖注入,则不应调用不在您注入的公共接口中的方法。如果你需要将接口的变量转换为具体的实现,那就意味着你做错了。

    【讨论】:

    • 我明白你的意思。设计失误。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 2023-04-02
    • 2011-05-22
    • 2013-09-21
    相关资源
    最近更新 更多