自定义 LifeStyle - IScopeAccessor

通过实现自定义 IScopeAccessor,你可以创建不同类型的范围。对于以下示例,我有两个类 FooBar,其中 Bar 将使用自定义 LifeStyle 注册。

每个人都有一个 ID 来协助测试

public class Foo
{
    public Guid FooId { get; } = Guid.NewGuid();
}

public class Bar
{
    public Guid BarId { get; } = Guid.NewGuid();
}

要将 Bar 注册为 LifestyleScoped<T>,我实施了 FooScopeAccessor

public class FooScopeAccessor : IScopeAccessor
{
    private static readonly ConcurrentDictionary<Foo, ILifetimeScope> collection = new ConcurrentDictionary<Foo, ILifetimeScope>();

    public ILifetimeScope GetScope(CreationContext context)
    {
        return collection.GetOrAdd(context.AdditionalArguments["scope"] as Foo, new DefaultLifetimeScope());
    }

    public void Dispose()
    {
        foreach (var scope in collection)
        {
            scope.Value.Dispose();
        }
        collection.Clear();
    }
}

注册和解决:

WindsorContainer container = new WindsorContainer();
container.Register(Component.For<Foo>().LifestyleTransient());

var foo1 = container.Resolve<Foo>(); // FooId = 004350ac-40ff-4d1a-8022-7977f94eb418
var foo2 = container.Resolve<Foo>(); // FooId = 714aad8a-e4a2-4950-9017-e387c1c56133

container.Register(Component.For<Bar>().LifestyleScoped<FooScopeAccessor>());

var bar1 = container.Resolve<Bar>(new Dictionary<string, Foo> { ["scope"] = foo1 });     
//                                              c144ba90-ce37-45c2-89d4-593d127fb723

var bar2 = container.Resolve<Bar>(new Dictionary<string, Foo> { ["scope"] = foo1 });
//                                              c144ba90-ce37-45c2-89d4-593d127fb723

var bar3 = container.Resolve<Bar>(new Dictionary<string, Foo> { ["scope"] = foo2 }); 
//                                              bcfe7ba4-cfb3-4b6e-8ecc-a3a3e5055bea

var bar4 = container.Resolve<Bar>(new Dictionary<string, Foo> { ["scope"] = foo1 }); 
//                                              c144ba90-ce37-45c2-89d4-593d127fb723

如上所述,使用 Foo1 解析的 bar2bar3 都是对同一个对象的引用,而 bar4 已经用 Bar 的新实例解析了

有关实现自定义 IScopeAccessor 的更多详细信息,请参阅 Castle 的文档