【发布时间】:2019-05-06 15:41:54
【问题描述】:
如下面的可运行代码示例所示,我想创建一个命名范围,其中解析对象的某个实例,而不考虑在创建对象后创建的其他未命名范围。
// You can't resolve a per-matching-lifetime-scope component
// if there's no matching scope.
using(var noTagScope = container.BeginLifetimeScope())
{
// This throws an exception because this scope doesn't
// have the expected tag and neither does any parent scope!
var fail = noTagScope.Resolve<Worker>();
}
在下面的示例中,父范围确实有匹配的标签,但它仍然不起作用。应该吗?
在下面的示例中,作用域是整洁的,并且父作用域是已知的 - 在我的应用程序中,只有根容器对象是可访问的,因此当创建作用域时,它始终来自容器而不是父作用域。
public class User
{
public string Name { get; set; }
}
public class SomeService
{
public SomeService(User user)
{
Console.WriteLine($"Injected user is named {user.Name}");
}
}
class Program
{
private static IContainer container;
private const string USER_IDENTITY_SCOPE = "SOME_NAME";
static void Main(string[] args)
{
BuildContainer();
Run();
Console.ReadKey();
}
private static void BuildContainer()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<SomeService>();
builder.RegisterType<User>().InstancePerMatchingLifetimeScope(USER_IDENTITY_SCOPE);
container = builder.Build();
}
private static void Run()
{
using (var outerScope = container.BeginLifetimeScope(USER_IDENTITY_SCOPE))
{
User outerUser = outerScope.Resolve<User>();
outerUser.Name = "Alice"; // User Alice lives in this USER_IDENTITY_SCOPE
SomeService someService = outerScope.Resolve<SomeService>(); // Alice
// Now we want to run a "process" under the identity of a different user
// Inside of the following using block, we want all services that
// receive a User object to receive Bob:
using (var innerSope = container.BeginLifetimeScope(USER_IDENTITY_SCOPE))
{
User innerUser = innerSope.Resolve<User>();
innerUser.Name = "Bob"; // We get a new instance of user as expected. User Bob lives in this USER_IDENTITY_SCOPE
// Scopes happen in my app that are unrelated to user identity - how do I retain User object despite this?
// The following is not a USER_IDENTITY_SCOPE -- We still want Bob to be the User object that is resolved:
using (var unnamedScope = container.BeginLifetimeScope())
{
// Crashes. Desired result: User Bob is injected
SomeService anotherSomeService = unnamedScope.Resolve<SomeService>();
}
}
}
}
}
使用 Autofac 4.9.2 / .net core 2.2
【问题讨论】:
标签: autofac