C# UnityContainer解决新实例问题
我有一门国际奥委会的课:C# UnityContainer解决新实例问题,c#,unity-container,C#,Unity Container,我有一门国际奥委会的课: public static class IoC { private static IUnityContainer container; private static void setupIoC() { container = new UnityContainer(); container.RegisterType<MessageContext>( new InjectionCo
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>();
}
}
公共静态类IoC
{
专用静态IUnityContainer容器;
私有静态void setupIoC()
{
容器=新的UnityContainer();
container.RegisterType(
新注入构造函数(
新数据库存储库(new RepositoryConfig(){AutoDetectionEnabled=false}));
}
公共静态T解析()
{
if(容器==null)
{
setupIoC();
}
返回container.Resolve();
}
}
在我的ViewModel中,我有:
public MessageViewModel()
: base(Resources.MENU_BAR_COREDATA_MESSAGE)
{
msgContext = IoC.Resolve<MessageContext>();
}
public MessageViewModel()
:base(参考资料。菜单\u栏\u核心数据\u消息)
{
msgContext=IoC.Resolve();
}
msgContext是一个实体框架抽象。。。如果我多次加载usercontrol,则存储库在DbSet.Local中有一些条目。如果我写
public MessageViewModel()
: base(Resources.MENU_BAR_COREDATA_MESSAGE)
{
msgContext = new MessageContext(new DatabaseRepository<Message>(new RepositoryConfig(){AutoDetectionEnabled = false}));
}
public MessageViewModel()
:base(参考资料。菜单\u栏\u核心数据\u消息)
{
msgContext=newmessagecontext(新数据库存储库(newrepositoryconfig(){AutoDetectionEnabled=false}));
}
我总是有一个新的msgContext没有任何数据库集。本地条目等。。。在我看来,这表明我的国际奥委会在解决问题时没有给我新的帮助。我使用UnityContainer,文档中说默认情况下它总是返回一个新实例
所以我不知道为什么它不能像我期望的那样工作。
我认为在注册期间,
新数据库存储库
只被调用一次您可以用injection factory替换injection构造函数:
container.RegisterType<MessageContext>(
new InjectionFactory( c =>
new MessageContext(
new DatabaseRepository<Message>(
new RepositoryConfig(){AutoDetectionEnabled = false} ) ) );
container.RegisterType(
新注射工厂(c=>
新消息上下文(
新数据库存储库(
新的RepositoryConfig(){AutoDetectionEnabled=false}));
不同之处在于,每次解析实例时都会执行工厂方法。嘿,Makubex,谢谢你的链接。但是我对{AutoDetectionEnabled=false}有一些问题,我该怎么写呢?如果我使用typeof(RepositoryConfig),我无法设置自动检测。。。