简体   繁体   English

使用autofac解析在运行时在构造函数中使用参数的类实例

[英]Resolve a class instance which takes parameters in constructor at run time using autofac

I'm following below example to create a class instance at runtime using autofac. 我在下面的示例中使用autofac在运行时创建类实例。 http://autofaccn.readthedocs.io/en/latest/advanced/delegate-factories.html http://autofaccn.readthedocs.io/en/latest/advanced/delegate-factories.html

But when running locally, I'm seeing an exception. 但是在本地运行时,我看到了一个异常。 I'm very new to autofac and let me know if I'm doing anything wrong here or if you need any more information. 我是autofac的新手,如果我在这里做错了什么,或者您需要更多信息,请告诉我。

Code structure: 代码结构:

public class ClassName
{
    public delegate ClassName Factory(Type1 obj1, string obj2);
    public ClassName(Type1 obj1, string obj2)
    {
        this.type1 = obj1;
        this.type2= obj2;
    }

    /*Some methods of this class that use type1 and type2*/
}

// Registration 
container.RegisterType<Type1>();
container.RegisterType<ClassName.Factory>();
container.RegisterType<ClassName>().AsSelf().InstancePerDependency();

// In some method to create an instance of ClassName
var factory = container.Resolve<Factory>(); // This is throwing the following exception.
var instance = factory(obj1Instance, "text"); // obj1Instance and "text" parameters cannot be determined at registration time.

The exception stackTrace: stackTrace异常:

Logging handled exception: Autofac.Core.DependencyResolutionException: Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = Factory (ReflectionActivator), Services = [ClassName+Factory], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'ClassName+Factory' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.Object object' of constructor 'Void .ctor(System.Object, IntPtr)'. (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'ClassName+Factory' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.Object object' of constructor 'Void .ctor(System.Object, IntPtr)'.
   at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable`1 parameters)
   at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
   --- End of inner exception stack trace ---
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
   at Autofac.Core.Resolving.InstanceLookup.Execute()
   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
   at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters)

The problem you have is that you're trying to register a factory. 您遇到的问题是您正在尝试注册工厂。 Autofac understands how to resolve a delegate, but it doesn't understand how to register it. Autofac知道如何解析委托,但不知道如何注册。

This should work: 这应该工作:

public class ClassName
{
    public delegate ClassName Factory(Type1 obj1, string obj2);
    public ClassName(Type1 obj1, string obj2)
    {
        this.type1 = obj1;
        this.type2= obj2;
    }
}

// Registration 
container.RegisterType<ClassName>().AsSelf().InstancePerDependency();

// In some method to create an instance of ClassName
var factory = container.Resolve<ClassName.Factory>();
var instance = factory.Invoke(obj1Instance, "text");

Edit: 编辑:

After running this myself I got the same exception but quickly realised what the issue was. 自己运行此程序后,我遇到了同样的异常,但很快意识到了问题所在。 Quoting autofac's entry on delegate factories I saw this: 引用autofac关于代表工厂的条目,我看到了:

By default, Autofac matches the parameters of the delegate to the parameters of the constructor by name 默认情况下,Autofac按名称将委托的参数与构造函数的参数进行匹配

The names of my constructor's parameters and my delegates' parameters didn't match which leads autofac to try and resolve the object by type, and since you haven't (and shouldn't unless you know you want to, and even so, you shouldn't) registered a string autofac 's Autofac.Core.Activators.Reflection.DefaultConstructorFinder fails. 我的构造函数的参数名称和代表的参数的名称不匹配,这导致autofac尝试按类型解析对象,并且由于您没有这样做(除非您知道autofac ,否则就不应该这样做,即使如此,您也是如此)不应)注册string autofacAutofac.Core.Activators.Reflection.DefaultConstructorFinder失败。

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

相关问题 Autofac在运行时使用构造函数参数解析通用类型 - Autofac resolve Generic type with constructor parameters at run time Autofac 使用不同的参数解析相同的 class 实例 - Autofac resolve the same class instance with different parameters 如何使autofac实时解析带有参数的构造函数? - How to make autofac resolve constructor with parameters in real time? Autofac通过指定的构造函数解析类 - Autofac resolve class by specified constructor Autofac从Container解析构造函数实例? - Autofac Resolve constructor instance from Container? 如何使用autofac在构造函数中向带有类的参数注入服务? - How to inject service to class with parameters in constructor using autofac? 如何使用带有构造函数参数的类注册依赖注入 - How to register a dependency injection with a class which takes constructor parameters 如何在autofac中传递有关解析时间的参数 - how to pass parameters on resolve time in autofac 当构造函数注入在配置和运行时已知参数时,从AutoFac获取类实例的最佳方法是什么 - What is the best way to get instance of a class from AutoFac when constructor injection has parameters known at configuration and runtime 如何使用参数构造函数动态创建实例,使用autofac DI解决 - How can I create instance Dynamically with parameter constructor resolve using autofac DI
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM