Конфигурация простого инжектора с DbContext в консольном приложении - PullRequest
0 голосов
/ 01 июня 2018

РЕДАКТИРОВАТЬ: Я дам еще одну попытку.Ниже приведен весь соответствующий код:

  //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, я получаю то же исключение.

...