Ninject BeginLifeTimeScope

时间:2012-10-05 19:24:06

标签: c# ninject autofac

是否存在使用Autofac的以下代码的Ninject等效项:

    public T Create<T>()
    {
        var requestScope =
            container.BeginLifetimeScope(
                builder => builder.RegisterType(typeof(T)).AsSelf());

        var viewModel = requestScope.Resolve<T>();

        lock (viewModelToContainersSyncLock)
        {
            viewModelsToContainers[viewModel] = requestScope;
        }

        return viewModel;
    }

1 个答案:

答案 0 :(得分:1)

<强> AutoFac:

您可以通过从根容器开始在任何现有生命周期范围内调用BeginLifetimeScope()方法来创建生命周期范围。终身范围是一次性的,它们跟踪组件处理,因此请确保始终呼叫&#34; Dispose()&#34;或者使用&#34;将它们包装在&#34;语句。

using(var scope = container.BeginLifetimeScope())
{
  // Resolve services from a scope that is a child
  // of the root container.
  var service = scope.Resolve<IService>();

  // You can also create nested scopes...
  using(var unitOfWorkScope = scope.BeginLifetimeScope())
  {
    var anotherService = unitOfWorkScope.Resolve<IOther>();
  }
}

<强> Ninject:

Ninject中有四个内置范围,其他一些范围通过扩展程序提供:Object-Scopes

据我所知,您所关注的最合理的范围是 InScope() 。 然后,您可以使用 .InScope(Func selectScope) 方法轻松定义自己的范围。

你可以创建这样的东西:

public class ScopeObject
{ }

public static class ProcessingScope
{
  public static ScopeObject Current {get; set;}
}

using Xunit;
public class NinjectCustomScopeExample
{
  public class TestService { }

  [Fact]
  public static void Test()
  {
    var kernel = new StandardKernel();
    kernel.Bind<ScopeObject>().ToSelf().InScope( x => ProcessingScope.Current );

    var scopeA = new ScopeObject();
    var scopeB = new ScopeObject();

    ProcessingScope.Current = scopeA;
    var testA1 = kernel.Get<ScopeObject>();
    var testA2 = kernel.Get<ScopeObject>();

    Assert.Same( testA2, testA1 );

    ProcessingScope.Current = scopeB;
    var testB = kernel.Get<ScopeObject>();

    Assert.NotSame( testB, testA1 );

    ProcessingScope.Current = scopeA;
    var testA3 = kernel.Get<ScopeObject>();

    Assert.Same( testA3, testA1 );
  }
}

希望这有帮助。