Autofac - how to resolve Func for ISomething from Singleton where ISomething is InstancePerHttpRequest

亡梦爱人 提交于 2019-11-30 02:31:34

I agree that this should work - the Func<IDataStore> is defining a factory that will produce the dependency in each method as required.

The way that I got around this method is to use the DependencyResolver.Current like the error message suggests. The main reason is that I already had it set up using the Autofac.Mvc4 nuget package...

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

So to actually setup the method I have the following func

public Func<T> PerHttpSafeResolve<T>()
{
    return () => DependencyResolver.Current.GetService<T>();
} 

And when constructing the container

builder.RegisterType<SuperDB>().As<IDataStore>().InstancePerHttpRequest();
builder.RegisterInstance(PerHttpSafeResolve<IDataStore>());

EDIT: The second line that is registering the instance is saying - If you need a Func<IDataStore> then use the value passed into the method. The result of the PerHttpSafeResolve<IDataStore> is just a function (factory), so it can live as a single instance.

The issue is the scope of the validators. Autofac always resolves SingleInstance dependencies from the application container, which means the validators' dependencies come from the application container as well.

Autofac is requesting the Func<IDataStore> instance from there, not from the request container. When you resolve IComponentContext you are getting the container in which the validator is being resolved: the application container. As Func<IDataStore> is scoped to a request, there is no way for Autofac to provide it at the application level, hence the error.

The correct approach is to register the validators as InstancePerHttpRequest. A component's lifetime is dictated by its longest-lived dependency; validators work best as singletons when they don't have dependencies. In this case, though, a validator which depends on IDataStore is constrained to live for at most the lifetime of the IDataStore instance. (On the bright side, you can get rid of the Func.)

Think about it like going to a party: if you catch a ride with the host, you have to stay there until the party is over. You can't ride with the host if you want to leave early.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!