1

是否有任何具有“子作用域”概念的 .NET DI 容器?

就像是:

var container = AppConfiguredContainer();

using(var childContainer = container.GetChild())
{
  childContainer.Register<IFoo>(typeof(Foo));

  // do stuff with childContainer
}

关键是在子容器中完成的任何服务配置都不会影响应用程序范围的配置。

4

1 回答 1

0

这是与 NInject 绑定的子作用域的示例:

var k = new StandardKernel();
k.Bind<Application>().ToSelf().InSingletonScope().DefinesNamedScope("Application");
k.Bind<UserRepository>().ToSelf().InNamedScope("Application");

const string userScopeName = "User";
k.Bind<UserScope>().ToSelf().DefinesNamedScope(userScopeName);
k.Bind<User>().ToSelf().InNamedScope(userScopeName);
k.Bind<User.ChatService>().ToSelf().InNamedScope(userScopeName);
k.Bind<User.SheetService>().ToSelf().InNamedScope(userScopeName);

const string nestedScopeName = "UserSheet";
k.Bind<User.Sheet>().ToSelf().DefinesNamedScope(nestedScopeName);
k.Bind<User.Sheet.SheetInfo>().ToSelf().InNamedScope(nestedScopeName);
k.Bind<User.Sheet.SheetCalculator>().ToSelf().InNamedScope(nestedScopeName);

您需要引用Ninject.Extensions.NamedScopeNinject.Extensions.Factorywith Ninject.Extensions.ContextPreservatioon

每个都Repository可以加载多个用户,并且每个用户都将Sheets在“子范围”中有多个:

public class UserRepository
{
    Func<UserScope> _factory;

    [Inject]
    public UserRepository(Func<UserScope> factory)
    {
        _factory = factory;
    }

    public UserScope LoadUser()
    {
        return _factory(); // scopes preserved
    }
}


public class User
{
    Func<Sheet> _sheetFactory; // multiple instances inside User scope
    public UserRepository Repository { get; } // same instance for app
    [Inject]
    public User(Func<Sheet> sheetFactory, UserRepository repository)
    {
        Repository = repository;
        _sheetFactory = sheetFactory;
    }

    public Sheet MakeSheet()
    {
        return _sheetFactory();
    }
}

UserScope将类用作容器很重要,User因为否则您无法User从其依赖项中解析相同的实例:

public class UserScope : IDisposable
{
    [Inject]
    public UserScope(User user, IResolutionRoot resolver)
    {
        User = user;
        Resolver = resolver;
    }

    public User User { get; }
    public IResolutionRoot Resolver { get; } // you can use this to resolve anything from inside **this** user scope
}

然后您可以加载用户,例如:

var app = k.Get<Application>(); // singleton
var u1 = app.Repository.LoadUser();
var u2 = app.Repository.LoadUser();

并且它们中的每一个都将具有相同的 and 实例,ApplicationRepository具有不同的ChatServiceand实例SheetService

于 2016-03-19T22:49:40.567 回答