Question

How to pass an unknown type which will be defined in another class as a parameter in such an expression. Don't know how to call the expression. and not sure why it can't remember the type between brackets and what's the solution.

.AddCallHandler<asp.CallHandlerType>

The Code :

 foreach (IAspect asp in Policy.Aspects)
 {
  //Type callHandlerType = asp.CallHandlerType;
  policy.AddMatchingRule(ruleLog)
    .AddCallHandler<asp.CallHandlerType>(new 
      ContainerControlledLifetimeManager());
 }

It's said the type or namespace for "asp" doesn't exist. Also I tried to define it earlier and pass it "callHandlerType", again a similar issue.

foreach asp the CallHandler type would be different, in one it would be RestaurantCallHandler, in the other it could be MagicCallHandler. Those were defined in aspects.

Interface's method definition :

public interface IAspect
{
   Type CallHandlerType { get; set; }
   // e.g it can be "MagicCallHandler : ICallHandler
}
Was it helpful?

Solution

In general if you don't know the type at compile you can use reflection to create a generic type at runtime.

However, in this case Unity provides non-generic method overloads (for most functionality) which accept argument(s) of type System.Type instead of generic type argument(s). This allows you to specify types at runtime or to use unbound generic types.

In your case you can use this code to register your call handlers with no reflection required:

foreach (IAspect asp in Policy.Aspects)
{
    policy.AddMatchingRule(ruleLog)
      .AddCallHandler(asp.CallHandlerType, 
        new ContainerControlledLifetimeManager());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top