从Windsor Container解析命名的datacontext组件

时间:2013-10-18 14:28:56

标签: c# asp.net-mvc asp.net-mvc-4 castle-windsor

我在容器中有两个注册:

container.Register(Component.For<DataContext>().LifestylePerWebRequest());
container.Register(Component.For<DataContext>().LifestyleTransient().Named("transientContext"));

我试图像这样解决命名实例(瞬态):

  var instance = Container.Instance.Resolve<DataContext>("transientContext");
  instance.Table1.Add(new Table1());
  instance.SaveChanges();

但在SaveChanges()中抛出异常“无效操作。连接已关闭。”

可能是什么问题?

THX!

1 个答案:

答案 0 :(得分:0)

我怀疑温莎正在混淆其中两种解决方法:

Container.Instance.Resolve<T>(object argumentAsAnonymousType) //the one its calling
Container.Instance.Resolve<T>(string key) //the one it should be calling

然后,Windsor将您的密钥“transientContext”视为DataContext的参数。 DataContext的参数是一个连接字符串ref,它导致实体框架抛出给定的异常。要解决此问题,您可以使用命名参数:

var instance = Container.Instance.Resolve<DataContext>(key: "transientContext");