Autofac.使用参数向构造函数注册类 [英] Autofac. Register class with constructor with params

查看:431
本文介绍了Autofac.使用参数向构造函数注册类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类自定义类:

public class MyClass: IMyClass{
    public MyClass(String resolverNamespace){
       //Do some stuff dependent on resolverNamespace
    }
    //... Other stuff
}

public interface IMyClass{
   //... Other stuff
}

我需要在autofac容器中注册它,以允许解析实例取决于调用者的名称空间. 那就是我期望的样子:

I need to register it in my autofac container to allow resolve instance depends on the namespace of caller. 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>();
      }
 }
 }

有什么想法吗?谢谢.

推荐答案

在注册中唯一能够做到这一点的方法是,将堆栈跟踪导航到原始调用站点,然后检查的命名空间.调用Resolve的类.如果不经常构造此对象,则可能是可以接受的.但是,如果该对象很可能被频繁构造,则您需要另一种方法.

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. 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.

我认为在Autofac中执行此操作的正确方法只是将命名空间作为构造函数参数传递:

I think the correct way to do this in Autofac is just to pass the namespace as a constructor parameter:

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

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

您可以进一步指定:

public class MyClass
{
   public MyClass(object namespaceProvider)
      : this (namespaceProvider.GetType().Namespace)
   { }
}

然后:

var factory = container.Resolve<Func<object, IMyClass>>();
var instance = factory(this);

使意图更明确

这篇关于Autofac.使用参数向构造函数注册类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆