Unity容器,解析为抽象类级别而不是顶级接口

时间:2014-11-19 04:52:06

标签: c# .net unity-container

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

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; }
        }
    }

1 个答案:

答案 0 :(得分:2)

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

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

ISomeInterface不是ActualWorker类型,而是实现ISomeInterface的包装类型。此类型无法转换为ActualWorker。

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