I have three linq queries, the first one just gets a list of assembly types which works fine. The second one I am having issues with. It is returning 0
results and I am not sure why.
Here is a query the first query that I use that gets reused:
var types = (
from assemblies in AppDomain.CurrentDomain.GetAssemblies()
from type in assemblies.GetTypes()
select type
).ToList();
Next I have this query which returns 0
results and I am not sure why:
var injectors = (
from type in types
from attrs in type.GetCustomAttributes<InjectAttribute>()
select attrs
).ToList();
The third query is almost exactly the same as the second query only it selects a different attribute. This one works:
(
from type in types
from attrs in type.GetCustomAttributes<InjectableAttribute>()
where attrs.ProvidedIn == ProvidedIn.Root
select type
).ToList().ForEach(service => {
var injector = injectors.Find(i => i.serviceType == service);
if (injector != null) {
var newService = Activator.CreateInstance(service);
services.Add(newService);
}
})
I am not sure why the second query works and the third does not...
Here is how I am using the two:
[Injectable(ProvidedIn = ProvidedIn.Root)]
public class Item { }
public class Test {
[Inject(typeof(Item))] Item item = null;
}
What I am trying to achieve, is in the foreach loop if one of the fields in the project has a [Inject]
attribute used with a particular type, then create an instance, otherwise don't create an instance. This is for a reusable classlib, so an inject type may or may not be used on the project that is consuming the library. If it isn't being used I don't want to create an instance of the [Injectable]
.
Side note: Is creating 3 separate Linq queries optimal, or I can I combine them into one query?
CodePudding user response:
Inject
is applied to members, not the type. To look for types whose members have that attribute you can use :
where type.GetMembers()
.SelectAny(mi=>mi.GetCustomAttributes<InjectAttribute>())
.Any()