如何检查IUnityContainer在运行时是否一致。

时间:2016-06-02 15:57:37

标签: c# unity-container

我想在完成所有类型后检查一个统一容器,看看某个类型是否缺失。这样做有合理的方法吗?

以下是一些示例代码,说明了我想要做的事情:

using Microsoft.Practices.Unity;
using System;

namespace MSUnityTest
{
    public interface INamed
    {
        string Name { get; }
    }
    public class GivenName : INamed
    {
        private string _name;
        public GivenName(string name)
        {
            _name = name;
        }
        public string Name { get { return _name; } }
    }

    public class NamePrinter
    {
        private INamed _entity;
        public NamePrinter(INamed entity) { _entity = entity; }
        public void run() { Console.WriteLine(_entity.Name); }
    }

    class Program
    {

        static IUnityContainer CheckedContainer()
        {
            IUnityContainer container = new UnityContainer();
            //suppose I forget the following line
            //container.RegisterType<INamed, GivenName>(new InjectionConstructor("Given Name"));
            //the container is now not in the State I want it to be
            container.RegisterType<NamePrinter, NamePrinter>();
            //can I detect that here?
            container.CheckTypesNowAndFailEarly(); //<-- this function does not exist
            return container;
        }

        static void Main(string[] args)
        {
            CheckedContainer().Resolve<NamePrinter>().run();
        }
    }
}

0 个答案:

没有答案