Autofac. Register a class with a constructor with parameters
I have a class class:
public class MyClass: IMyClass{
public MyClass(String resolverNamespace){
//Do some stuff dependent on resolverNamespace
}
//... Other stuff
}
public interface IMyClass{
//... Other stuff
}
I need to register it in the autofac container to allow the permission instance depended on the caller's namespace. What I expect should be:
//Registering in autofac
builder.Register(x=>new MyClass(x.ResolveCallerNamespace)).As(IMyClass);
// Somewhere in application
namespace SomeNamespace{
public SomeClass{
public void SomeMethod(){
{
// Here i need to resolve MyClass instance(calling new MyClass("SomeNamespace"))
var instance = container.Resolve<IMyClass>();
}
}
}
Any idea? thank.
source to share
The only way you can do this when registering is to move the stack trace to the original site of the call and then examine the namespace of the class in which the call was made Resolve
. If this facility is built infrequently, then this is probably acceptable. However, if the object is likely to be built very often, you need a different approach.
Also, you should be aware that this approach is fragile, since you cannot guarantee how the caller can resolve the instance.
I think the correct way to do it in Autofac
is to simply pass the namespace as a parameter to the constructor:
builder.RegisterType<MyClass>().As<IMyClass>();
public SomeClass
{
public void SomeMethod()
{
var factory = container.Resolve<Func<string, IMyClass>>();
var instance = factory(this.GetType().Namespace);
}
}
You can go ahead and specify:
public class MyClass
{
public MyClass(object namespaceProvider)
: this (namespaceProvider.GetType().Namespace)
{ }
}
Then:
var factory = container.Resolve<Func<object, IMyClass>>();
var instance = factory(this);
Makes intent more explicit.
source to share