UnityContainer 解决新建实例问题

UnityContainer Resolve new instance issue

我有这个 IoC-class:

public static class IoC
{
    private static IUnityContainer container;

    private static void setupIoC()
    {
        container = new UnityContainer();
        container.RegisterType<MessageContext>(
            new InjectionConstructor(
                 new DatabaseRepository<Message>(new RepositoryConfig() {AutoDetectionEnabled = false})));

    }

    public static T Resolve<T>()
    {
        if (container == null)
        {
            setupIoC();
        }
        return container.Resolve<T>();
    }
}

在我的 ViewModel 中我有:

public MessageViewModel()
    : base(Resources.MENU_BAR_COREDATA_MESSAGE)
{
    msgContext = IoC.Resolve<MessageContext>();
}

msgContext 是一个 Entity Framework 抽象...如果我多次加载用户控件,存储库在 DbSet.Local 中有一些条目。如果我写

public MessageViewModel()
    : base(Resources.MENU_BAR_COREDATA_MESSAGE)
{
    msgContext = new MessageContext(new DatabaseRepository<Message>(new RepositoryConfig(){AutoDetectionEnabled = false}));
}

我总是有一个全新的 msgContext,没有任何 DbSet.Local 条目等...在我看来,这表明我的 IoC 在解析它时没有给我一个新的实例。我使用 UnityContainer 并且文档说它总是 returns 默认情况下是一个新实例...

所以我不知道为什么它没有像我预期的那样工作。

When is the Unity InjectionConstructor acually run?

我认为 new DatabaseRepository 在注册过程中只调用了一次

您可以将注入构造函数替换为注入工厂:

   container.RegisterType<MessageContext>(
        new InjectionFactory( c =>
             new MessageContext(
                   new DatabaseRepository<Message>(
                         new RepositoryConfig(){AutoDetectionEnabled = false} ) ) );

区别在于每次解析实例时都会执行工厂方法。