2016-01-06 41 views
2

我有這樣的IoC級:UnityContainer解決新問題,例如

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是實體框架抽象...如果我加載用戶控件不止一次,存儲庫在DbSet.Local中有一些條目。如果我寫

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

我總是沒有任何DbSet.Local條目等一個全新的msgContext ......在我看來,它是我的國際奧委會並沒有給我一個新的instace當我解決這個問題的一個指標。我使用的UnityContainer和文件說,它總是會默認返回一個新的實例...

所以我不知道爲什麼它不工作,因爲我所期望的。

回答

2

期間只調用一次你可以更換注射構造與注塑廠:

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

不同的是,在每次執行的工廠方法實例已解決。