在控制台应用程序中使用DbContext进行简单的Injector配置

时间:2018-06-01 19:20:46

标签: simple-injector

修改 我会再试一次。以下是所有相关代码:

  //in BaseProject for other console apps (a class library):
    public class SimpleInjectorInitializer
    {
      public static Container MakeContainer()
      {
        Container container = new Container()
        container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle(); //Also tried with asyncScopedLifestyle, various combinations of these two
    container.Options.DefaultLifestyle = new ThreadScopedLifestyle();

    container.Register<MyRoot>();
    container.Register<ISomeOther, SomeOtherStuff>()
    //etc.

   container.Register<IMyDbContext, MyDbContext>(Lifestyle.Scoped);

   container.Verify();

   return container;    
  }
}

//In DependentConsoleApp, which references the above project:
class Program
{
  private static Container _container;

  static Program
  {
    _container = SimpleInjectorInitializer.MakeContainer();
  }

  static void Main(string[] args)
{
  var myRoot = _container.GetInstance<MyRoot>();
  myRoot.DoStuff();
}

除了上面的两个类在不同的项目中,接口及其实现在不同的项目中,DbContexts及其接口在不同的项目中。

在调用_container.GetInstance<>()时,我得到以下异常和堆栈跟踪:

SimpleInjector.ActivationException: 'The MyRoot is registered as 'Thread Scoped' lifestyle, but the instance is requested outside the context of an active (Thread Scoped) scope.'

   at SimpleInjector.Scope.GetScopelessInstance[TImplementation](ScopedRegistration`1 registration)
   at SimpleInjector.Scope.GetInstance[TImplementation](ScopedRegistration`1 registration, Scope scope)
   at SimpleInjector.Advanced.Internal.LazyScopedRegistration`1.GetInstance(Scope scope)

当我尝试AsyncScopedLifestyle时,我得到了相同的异常。

0 个答案:

没有答案