0

是否有使用 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;
    }
4

1 回答 1

1

AutoFac:

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

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 中有四个内置作用域,还有一些通过扩展提供的其他作用域:对象作用域

据我了解您的问题,您追求的最合理范围是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 );
  }
}

希望这可以帮助。

于 2016-02-25T10:28:25.207 回答