What is the right way to abstract out Autofac's factory method support?
I keep getting this exception:
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.
Here is my attempt to wrap it up.
public void Register<T>(Func<IFactoryContext, T> factoryMethod)
{
_containerBuilder.Register<Func<Type, T>>(c => {
var ctx = c.Resolve<IComponentContext>();
return request => factoryMethod(new AutofacFactoryContext(ctx));
});
}
I've even tried
public void Register<T>(Func<IFactoryContext, T> factoryMethod)
{
_containerBuilder.Register<Func<Type, T>>(c => {
var ctx = c.Resolve<IComponentContext>();
return request => factoryMethod(new AutofacFactoryContext((IComponentContext)ctx.Resolve(request)));
});
}
I want to have a method that returns T
.
AutofacFactoryContext
is an implementation of IFactoryContext
, which is just a wrapping of Autofac's IComponentContext
.
In the end this is the result I'm expecting:
bootstrapper.Register<IFoo>(c => new Foobar());
In using the container:
var foobar = container.Resolve<IFoo>();
I guess the following would work:
public void Register<T>(Func<IFactoryContext, T> factoryMethod)
{
_containerBuilder.Register<Func<Type, T>>(c =>
request => {
var ctx = c.Resolve<IComponentContext>();
factoryMethod(new AutofacFactoryContext(ctx));
});
}
However, please note that this would make no use of the request
, just like your first example. As I am not really sure what you are trying to achieve here, I can't propose a better alternative.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.