简体   繁体   English

Autofac。 使用参数向构造函数注册类

[英]Autofac. Register class with constructor with params

I have the class custom 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 my autofac container to allow resolve instance depends on the namespace of caller. 我需要在autofac容器中注册它,以允许解析实例取决于调用者的名称空间。 Thats how I expect it 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? 任何想法? Thx. 谢谢。

The only way you are going to be able to do that in the registration is by navigating up the stack trace to the original call site and then examine the namespace of the class where the Resolve call was made. 在注册中唯一能够做到这一点的方法是,将堆栈跟踪导航到原始调用站点,然后检查进行Resolve调用的类的名称空间。 If this object is constructed infrequently, then that is probably acceptable. 如果不经常构造此对象,则可能是可以接受的。 However if the object is likely to be constructed very often then you need another approach. 但是,如果对象很可能被频繁构造,则需要另一种方法。

Also you should be aware that this approach is fragile as you can't guarantee how the caller will resolve the instance. 另外,您还应该意识到这种方法是脆弱的,因为您不能保证调用者将如何解析实例。

I think the correct way to do this in Autofac is just to pass the namespace as a constructor parameter: 我认为在Autofac执行此操作的正确方法只是将名称空间作为构造函数参数传递:

builder.RegisterType<MyClass>().As<IMyClass>();

public SomeClass
{
    public void SomeMethod()
    {
         var factory = container.Resolve<Func<string, IMyClass>>();
         var instance = factory(this.GetType().Namespace);
    }
}

You could go further 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 the intention more explicit. 使意图更加明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM