ACTNARS fails to resolve closed generics with abstract type argument
I still have problem with #855 in cases of Foo<Bar> where Bar is abstract class.
simply doing
public class Foo<T> { }
public abstract class Bar {}
and trying to resolve Foo<Bar> with ACTNARS gives me exception that type is not registered
Do you have a small repro we can try in unit test form? Which version of Autofac are you using?
Not really, I can create one if you want, but I've literally posted all the code above. It was on 4.8.1. And 4.1.1 is the latest one where it works.
It would help, so please do. I just want to make sure we're both on the same page with what's going wrong and that I can see what you're seeing. For example, you're saying you get an exception that "the type is not registered" but you have two types listed. What's the exception stack message with stack trace? Is it happening at resolve time? Which thing are you trying to resolve? That could all be clarified with a quick unit test repro. Thanks!
Sure, here is the demo code https://github.com/Codelet/AutofacACTNARS
For reference, here's the repro code from the repo:
namespace AutofacACTNARS
{
using Autofac;
using Autofac.Features.ResolveAnything;
public class Foo<T>
{
}
public class Bar1
{
}
public abstract class Bar2
{
}
public class Program
{
public static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
var container = builder.Build();
var thisWorks = container.Resolve<Foo<Bar1>>(); // OK, Bar1 is not abstract
var thisDoesnt = container.Resolve<Foo<Bar2>>(); // Throws, Bar2 is abstract, but there is no code that would use it
}
}
}
Based on that, the challenge is definitely around abstract types (as the title of the issue notes), which is slightly different but related to #855.
On a side note, I think you'd have to define the open generic as Foo<out T> to allow it to be used. I doubt that'd make a difference here, but it's something to be aware of.
It looks like it comes down to this in ACTNARS:
if (typeInfo.IsGenericType)
{
foreach (var typeParameter in typeInfo.GenericTypeArguments)
{
// Issue #855: If the generic type argument doesn't match the filter don't look for a registration.
if (_predicate(typeParameter) && !registrationAccessor(new TypedService(typeParameter)).Any())
{
return Enumerable.Empty<IComponentRegistration>();
}
}
}
Basically, "If it hasn't been filtered out and we can find a registration for the type, let it through."
But ACTNARS by default doesn't provide registrations for abstract types:
if (!typeInfo.IsClass ||
typeInfo.IsSubclassOf(typeof(Delegate)) ||
typeInfo.IsAbstract ||
typeInfo.IsGenericTypeDefinition ||
!_predicate(ts.ServiceType) ||
registrationAccessor(service).Any())
{
return Enumerable.Empty<IComponentRegistration>();
}
It also doesn't provide registrations for other non-concrete types like interfaces. For example, this won't work:
container.Resolve<Foo<IComparable>>()
I feel like we should maybe change that. If it's a generic type argument and it's not filtered out, sure, we can provide a registration for it. However, when you try to resolve it, if the constructor actually needs to be filled in with one of these types that can't be constructed (like, we can't "new up" an abstract class) then you'd get a runtime error.
Pretty sure it's related to fix #495 (also #855 was a fix for it). Before #495(at least before 4.2.0, but it seems related) it worked as is in example code with no changes. Of course if I put Bar2 in constructor it must fail and that's pretty much expected :) But if I use that generic argument as method input parameter or something where my code forwards the exact instance, it should not be a problem to construct such instance, because it's not going to instantiate the abstract type.
OK, it's taken me a bit of research to dive in here and it doesn't look like this is a simple answer. I'm remembering running into this before.
The problem boils down to the fact that ACTNARS works based on the order in which it was registered.
The issues in question:
- #495: The
AnyConcreteTypeNotAlreadyRegisteredSourcethrows an exception when tries to Resolve unregisteredMeta<T>types - #855: ACTNARS fails to resolve closed generics
So, say you're resolving IEnumerable<Meta<Bar1>> - ACTNARS should not handle the IEnumerable<T> or Meta<T> wrappers in there, but the system wants Bar1 to be registered because otherwise how could you get metadata from it? Further, the stuff that provides IEnumerable<T>, Meta<T>, Lazy<T>, and other support... there's a lot to it. It's not super feasible to create an "exception list" of special cases that ACTNARS should know about. Not to mention you can technically create a container that removes that default behavior.
That's the logic behind checking to see if the type parameters can be handled: Avoid special cases around the common built-in relationship types yet still provide support for other generics where possible.
However, when it comes to things that aren't provided by the other registration sources, we don't care about the type parameters. So the case of Foo<Bar2> should technically work. Foo<T> is handled by ACTNARS and Bar2 is never instantiated.
I tried removing the check I noted above about if(typeInfo.IsGenericType) where it checks the generic type arguments, but while it allowed the Foo<Bar2> bit to work, it stopped allowing IEnumerable<Meta<T>> to be resolved.
On a larger scale, this appears to be a potential challenge with the way registration sources are handled and the overall resolution pipeline works. It's not like middleware. If it was, I could see a solution like this:
- Pipeline created with: ACTNARS =>
IEnumerable<T>=>Meta<T> - Resolve starts for
IEnumerable<Meta<Bar1>> - ACTNARS skips its turn.
IEnumerable<T>source says it can handle theIEnumerable<T>part if theMeta<Bar1>can be handled. Can it? a. Resolve starts forMeta<Bar1>. b. ACTNARS skips its turn. c.IEnumerable<T>source says it can't do anything, skips. d.Meta<T>says it can handle the request, returns the registration.IEnumerable<T>says it can handle the request, returns the registration.- ACTNARS sees the registration is handled, allows the registration to pass through.
Basically, ACTNARS would allow pass-through if something else handles the request. When it doesn't...
- Pipeline created with: ACTNARS =>
IEnumerable<T>=>Meta<T> - Resolve starts for
Foo<Bar2>> - ACTNARS skips its turn.
IEnumerable<T>source says it can't do anything, skips.Meta<T>source says it can't do anything, skips.- ACTNARS catches the empty set of registrations on the way back out. Nothing else could handle it, so ACTNARS says it can take it. ACTNARS returns the registration.
The idea there being that ACTNARS would only handle something that isn't already handled elsewhere.
Unfortunately, that's not how it works. Instead, it's a foreach loop over a set of sources that don't know anything about each other. In pseudo-code:
foreach(var source in sources)
{
var registration = source. RegistrationsFor(service);
if(registration != null)
{
break;
}
}
Registration sources get processed from most-to-least recent registration. ACTNARS gets hit before other sources since it's registered long after the IEnumerable<T> and Meta<T> sorts of sources, so if we don't do the checks on the parameters, it assumes control. Once it does that... IEnumerable<T> and others stop working.
I've added a failing/skipped test to the ResolveAnythingTests fixture so we can look into this further, but after spending a bit of time with it this doesn't seem like a "quick fix."
Middleware approach is nice, but I assume it's a hard refactoring.
Maybe easier suggestion - to treat ACTNARS as a special default registration source. Similar to the one that resolve IEnumerable<> and Meta<>. Final user doesn't add them manually, it's done automatically by the ContainerBuilder.
Thus instead of letting final user register ACTNARS manually it's possible to make ContainerBuilder to do that in RegisterDefaultAdapters.
Of course not everyone may want the ACTNARS functionality to be always there, thus there might be a constructor flag in ContainerBuilder that would indicate if ACTNARS should be pushed as the very first default registration source (and thus is the last to hit during resolution).
Another option is to have a method on ContainerBuilder, something like RegisterAnyConcreteTypeNotAlreadyRegistered (sorry, I'm not the best one in naming), which would also set the flag to indicate ACTNARS should be pushed during RegisterDefaultAdapters.
If I understood it right in this case you can remove the check you mentioned inside ACTNARS, which will fix this issue and still keep other default adapters working properly.
It's not just abstract types, it's also interface types. Basically, if a generic type parameter can't be resolved, ACTNARS fails even if the type parameter isn't used in the constructor.
#1027 cropped up a little ago on this, too.
I forgot about all the little nuances here. Still not sure how to solve it the right way.
We have the same problem with resolving Foo<string> or Foo<int>.