Search code examples
dependency-injectioncastle-windsoraspnetboilerplate

How to resolve parameterized class at runtime?


I have a view model like this:

public ViewModelSample(MyClass a)
{
}

I tried to resolve this by:

var myClassObj = new MyClass();
var vm = IocManager.Resolve<T>(myClassObj); // where args = object of MyClass

Signature IIocResolver . T Resolve<T> (object argumentsAsAnonymousType);

If I were to do this from System.Activator, then I would call return (T)Activator.CreateInstance(typeof(T), myClassObj); and it works fine.

Also, if ViewModelSample is only having parameterless constructor, then it does resolve it fine.

I am getting the exception:

Missing dependency. Component ViewModels.ViewModelSample has a dependency on Dto.MyClass, which could not be resolved. Make sure the dependency is correctly registered in the container as a service, or provided as inline argument.

MyClass is a simple DTO, so it's not inheriting ITransientDependency. Moreover, I want to assign this value at runtime.

How do I solve this?


Solution

  • Signature IIocResolver . T Resolve<T> (object argumentsAsAnonymousType);

    In this case, new { a = myClassObj } since a is the name of your parameter.

    var vm = IocManager.Resolve<ViewModelSample>(new { a = myClassObj });
    

    Reference

    Anonymous Types: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types