我正在尝试创建一个"A(UserManager) 需要创建 B(UserClient) 的实例"的关系(http://code.google.com/p/autofac/wiki/RelationshipTypes),其中B(UserClient)需要HttpSessionStateBase。
用户客户端
这是注册Autofac的地方。
我会尽力协助您进行翻译。以下是需要翻译的内容:
错误 2
我已经尝试了将
用户客户端
public class UserClient : IUserClient
{
public UserClient(HttpSessionStateBase session)
{
//...
}
//...
}
用户管理器
public class UserManager : IUserManager
{
private readonly Func<IUserClient> userClientPerRequest;
private IUserClient UserClient
{
get
{
return userClientPerRequest();
}
}
public UserManager(Func<IUserClient> userClientPerRequest)
{
this.userClientPerRequest = userClientPerRequest;
}
public void DoStuff()
{
UserClient.DoStuff();
}
这是注册Autofac的地方。
public class MyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<UserManager>().As<IUserManager>().SingleInstance();
builder.RegisterType<UserClient>().As<IUserClient>().InstancePerHttpRequest();
builder.RegisterModule(new AutofacWebTypesModule());
//If i try this, i get Error 1 (printing errors after this code-block)
builder.Register<Func<IUserClient>>(c => c.Resolve<IUserClient>);
//If i try this, i get Error 2
builder.Register<Func<IUserClient>>(c => {
var ctx = c.Resolve<IComponentContext>();
return ctx.Resolve<IUserClient>;
});
//If i try this, well i always get null from GetService..
builder.Register<Func<IUserClient>>(c =>
DependencyResolver.Current.GetService<IUserClient>);
}
我会尽力协助您进行翻译。以下是需要翻译的内容:
看 Autofac: 从 SingleInstance'd 类型到 HttpRequestScoped 的参考,它们使用了一些 RequestContainer
,但我找不到这个东西。:)
错误1
This resolve operation has already ended. When registering components using lambdas, the IComponentContext 'c' parameter to the lambda cannot be stored. Instead, either resolve IComponentContext again from 'c', or resolve a Func<> based factory to create subsequent components from.
错误 2
No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being reqested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
我已经尝试了将
.InstancePerHttpRequest()
切换为.InstancePerLifetimeScope()
,以及其他许多不同的方法... 有人有什么想法吗?谢谢。