How to setup a Unity Registration Convention? - c#

With structure map, you can register a convention that lets you not just tweak the type, but also intervene during object creation. How can I do this with Unity.
public class SettingsRegistration : IRegistrationConvention
{
public void Process(Type type, Registry registry)
{
if (!type.IsAbstract && typeof(ISettings).IsAssignableFrom(type))
{
registry.For(type).Use(x =>
{
var svc = x.GetInstance<ISettingService>();
return svc.LoadSetting(type);
});
}
}
}

You can do this with a combination of Unity's Registration by Convention and an InjectionFactory. I see three common options for implementation, though I'm sure there are more...
Option 1
Register all type at once with if conditions inline in a lambda expression. Though this does not scale well if you are registering many types with many custom registrations...
container.RegisterTypes(
AllClasses.FromLoadedAssemblies(),
WithMappings.FromAllInterfaces,
WithName.Default,
WithLifetime.Transient,
type =>
{
// If settings type, load the setting
if (!type.IsAbstract && typeof (ISettings).IsAssignableFrom(type))
{
return new[]
{
new InjectionFactory((c, t, n) =>
{
var svc = (ISettings) c.Resolve(t);
return svc.LoadSetting(t);
})
};
}
// Otherwise, no special consideration is needed
return new InjectionMember[0];
});
Option 2
Register only the ISettings types and supply some nice helper methods. You will need to call container.RegisterTypes multiple times, but it is much more readable...
container.RegisterTypes(
AllClasses.FromLoadedAssemblies().IsSetting(),
WithMappings.FromAllInterfaces,
WithName.Default,
WithLifetime.Transient,
SettingsRegistration.InjectionMembers);
...
public static class SettingsRegistration
{
public static IEnumerable<Type> IsSetting(this IEnumerable<Type> types)
{
return types.Where(type => !type.IsAbstract &&
typeof (ISettings).IsAssignableFrom(type));
}
public static IEnumerable<InjectionMember> InjectionMembers(Type type)
{
return new[] {new InjectionFactory(LoadSetting)};
}
public static ISettings LoadSetting(IUnityContainer container,
Type type,
string name)
{
var svc = (ISettings) container.Resolve(type, name);
return svc.LoadSetting(type);
}
}
Option 3
Or you could create a class derived from RegistrationConvention and let that class make all of the registration decisions...
container.RegisterTypes(new SettingsRegistrationConvention(
AllClasses.FromLoadedAssemblies()));
...
public class SettingsRegistrationConvention : RegistrationConvention
{
private readonly IEnumerable<Type> _scanTypes;
public SettingsRegistrationConvention(IEnumerable<Type> scanTypes)
{
if (scanTypes == null)
throw new ArgumentNullException("scanTypes");
_scanTypes = scanTypes;
}
public override IEnumerable<Type> GetTypes()
{
return _scanTypes.Where(type => !type.IsAbstract &&
typeof (ISettings).IsAssignableFrom(type));
}
public override Func<Type, IEnumerable<Type>> GetFromTypes()
{
return WithMappings.FromAllInterfaces;
}
public override Func<Type, string> GetName()
{
return WithName.Default;
}
public override Func<Type, LifetimeManager> GetLifetimeManager()
{
return WithLifetime.Transient;
}
public override Func<Type, IEnumerable<InjectionMember>> GetInjectionMembers()
{
return type => new[]
{
new InjectionFactory((c, t, n) =>
{
var svc = (ISettings) c.Resolve(t);
return svc.LoadSetting(t);
})
};
}
}

Related

Adding a list of types to service builder

I am trying to take a namespace find all the classes that end with service then add them as a singleton to my service.
foreach(Type serviceClass in GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyProject.Services"))
{
services.AddSingleton<serviceClass.GetType()>;
}
This does not compile, so any help would be appreciated.
The best approach that I found is based on this.
Would required some mother methods and classes:
You need to call this inside you Configure:
services.RegisterAssemblyPublicNonGenericClasses()
.Where(c => c.Namespace == "")
.AsPublicImplementedInterfaces();
Create this class:
public class AutoRegisteredResult
{
internal AutoRegisteredResult(Type classType, Type interfaceType)
{
Class = classType;
Interface = interfaceType;
}
public Type Class { get; }
public Type Interface { get; }
}
And these methods:
public static IEnumerable<Type> RegisterAssemblyPublicNonGenericClasses(this IServiceCollection services,
params Assembly[] assemblies)
{
if (assemblies.Length == 0)
assemblies = new[] { Assembly.GetCallingAssembly() };
var allPublicTypes = assemblies.SelectMany(x => x.GetExportedTypes()
.Where(y => y.IsClass && !y.IsAbstract && !y.IsGenericType && !y.IsNested));
return allPublicTypes;
}
public static IList<AutoRegisteredResult> AsPublicImplementedInterfaces(this IEnumerable<Type> autoRegData)
{
var result = new List<AutoRegisteredResult>();
foreach (var classType in autoRegData)
{
var interfaces = classType.GetTypeInfo().ImplementedInterfaces;
foreach (var infc in interfaces)
{
result.Add(new AutoRegisteredResult(classType, infc));
}
}
return result;
}

Proper run-time construction pattern for large number of objects

What is the best way to create derived objects at run-time while adhering to LSP and always keeping the objects in a valid state.
I'm fairly new to construction patterns such as Factory and Builder and most of the examples I find are very simplistic. Here is my scenario:
I have one base class (some things left out for brevity):
public abstract BaseClass
{
public string Property1 { get; set ... null guard; }
public string Property2 { get; set ... conditional null guard; }
public virtual bool RequiresProperty2 => false;
protected BaseClass(string property1)
{
null guard
Property1 = property1;
}
}
I have 50+ derived classes. Some of which require prop2 some of which don't. The ones that require prop2 have a constructor that forces prop2 to be passed in, enforcing that all BaseClass derived objects are in a valid state upon construction. I'm also trying to adhere to LSP and I'm using Castle Windsor for dependency injection.
The solution I've come up with is to create a factory that returns a builder:
public interface IFactory
{
IBuilder Create(string type);
}
public interface IBuilder
{
IBuilder SetProperty1(string property);
IBuilder SetProperty2(string property);
BaseClass Build();
}
The concrete implementation of the factory loads all the types that inherit from BaseClass through reflection. When you call Factory.Create(...) you pass it a string which is the string name of the type you want to create. Then the factory creates a builder passing the appropriate Type to the builder's constructor. The builder looks like so:
public sealed class ConcreteBuilder : IBuilder
{
private static Type ClassType = typeof(BaseClass);
private static readonly ConcurrentDictionary<Type, Delegate>
ClassConstructors = new ConcurrentDictionary<Type, Delegate>();
private readonly Type type;
private string property1;
private string property2;
public ConcreteBuilder(Type type)
{
if (type == null) throw new ArgumentNullException(nameof(type));
if (!type.IsSubclassOf(ClassType))
{
throw new ArgumentException("Must derive from BaseClass.");
}
this.type = type;
}
public IBuilder SetProperty1(string property)
{
this.property1 = property;
return this;
}
public IBuilder SetProperty2(string property)
{
this.property2 = property;
return this;
}
public BaseClass Build()
{
var arguments = BuildArguments();
Delegate ctor;
if (ClassConstructors.TryGetValue(this.type, out ctor))
{
return (BaseClass)ctor.DynamicInvoke(arguments);
}
return (BaseClass)GetConstructor(arguments).DynamicInvoke(arguments);
}
private object[] BuildArguments()
{
var args = new List<object>();
if (!string.IsNullOrEmpty(this.property1))
{
args.Add(this.property1);
}
if (!string.IsNullOrEmpty(this.property2))
{
args.Add(this.property2);
}
return args.ToArray();
}
private Delegate GetConstructor(object[] arguments)
{
var constructors = this.type.GetConstructors();
foreach (var constructor in constructors)
{
var parameters = constructor.GetParameters();
var parameterTypes = parameters.Select(p => p.ParameterType).ToArray();
if (parameterTypes.Length != arguments.Length + 1) continue;
if (!parameterTypes.Zip(arguments, TestArgumentForParameter).All(x => x))
{
continue;
}
var parameterExpressions = parameters.Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray();
var callConstructor = Expression.New(constructor, parameterExpressions);
var ctor = Expression.Lambda(callConstructor, parameterExpressions).Compile();
ClassConstructors.TryAdd(this.type, ctor);
return ctor;
}
throw new MissingMethodException("No constructor found");
}
private static bool TestArgumentForParameter(Type parameterType, object argument)
{
return (argument == null && !parameterType.IsValueType) || (parameterType.IsInstanceOfType(argument));
}
}
Is there a better way to do this? Am I going about this the right way? I know DynamicInvoke is slow. Should I be going about this differently?

Automatically Registering All Implementations of a Generic Interface

My current registration code:
Assembly web = Assembly.Load("MyAssembly");
types.AddRange(web.GetTypes());
//etc.
foreach (var theInterface in types.Where(t => t.IsInterface))
{
var assignableType = types.Where(t => theInterface.IsAssignableFrom(t) && t != theInterface);
foreach (var type in assignableType)
{
container.RegisterType(theInterface, type);
}
}
My generic interface and its implementations:
public interface IDomainEventHandler<in T>
{
void Handle(T message);
}
public class DomainEventHandler1 : IDomainEventHandler<PhilTest1>
{
public void Handle(PhilTest1 message)
{
throw new System.NotImplementedException();
}
}
public class DomainEventHandler2 : IDomainEventHandler<PhilTest2>
{
public void Handle(PhilTest2 message)
{
throw new System.NotImplementedException();
}
}
public class DomainEventHandler3 : IDomainEventHandler<PhilTest2>
{
public void Handle(PhilTest2 message)
{
throw new System.NotImplementedException();
}
}
public class PhilTest1
{
}
public class PhilTest2
{
}
Here is a simplified version of how I would resolve:
IEnumerable<IDomainEventHandler<PhilTest2>> listeners = Container.ResolveAll<IDomainEventHandler<PhilTest2>>();
IEnumerable<IDomainEventHandler<PhilTest1>> listeners2 = Container.ResolveAll<IDomainEventHandler<PhilTest1>>();
This doesn't work--listeners and listeners2 are both empty after resolving. This is not unexpected.
In Windsor, I could do something like this:
container.Register(AllTypes.FromAssemblyNamed("MyAssembly").BasedOn(typeof(IDomainEventHandler<>)).WithService.Base());
How would I register all instances of IDomainEventHandler in Unity? I'd prefer to keep the existing registration code intact (if possible).
A bit painful, but I finally pieced it together via googling and debugging:
Registration:
IEnumerable<Type> handlers = types.Where(t => IsAssignableToGenericType(t, typeof(IDomainEventHandler<>)) && !t.IsInterface);
foreach (var handler in handlers)
{
container.AddNewExtension<OpenGenericExtension>()
.Configure<IOpenGenericExtension>()
.RegisterClosedImpl(typeof (IDomainEventHandler<>), handler);
}
IsAssignableToGenericType method:
private static bool IsAssignableToGenericType(Type givenType, Type genericType)
{
var interfaceTypes = givenType.GetInterfaces();
foreach (var it in interfaceTypes)
{
if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType)
return true;
}
if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
return true;
Type baseType = givenType.BaseType;
if (baseType == null) return false;
return IsAssignableToGenericType(baseType, genericType);
}
And the Extension. Note that if I didn't use a name for the registration, only one type would remain registered. I believe this is by design?
public interface IOpenGenericExtension : IUnityContainerExtensionConfigurator
{
void RegisterClosedImpl(Type openGenericInterface, Type closedType);
}
public class OpenGenericExtension : UnityContainerExtension, IOpenGenericExtension
{
protected override void Initialize() {}
public void RegisterClosedImpl(Type openGenericInterface, Type closedType)
{
closedType.GetInterfaces().Where(x => x.IsGenericType)
.Where(x => x.GetGenericTypeDefinition() == openGenericInterface)
.ToList()
.ForEach(x => Container.RegisterType(x, closedType, closedType.Name));
}
}

Dynamically load a class without specifying the assembly [duplicate]

Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?
This is what I want to re-write:
foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
Mine would be this in c# 3.0 :)
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
Basically, the least amount of iterations will always be:
loop assemblies
loop types
see if implemented.
This worked for me. It loops though the classes and checks to see if they are derrived from myInterface
foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
.Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {
//do stuff
}
I appreciate this is a very old question but I thought I would add another answer for future users as all the answers to date use some form of Assembly.GetTypes.
Whilst GetTypes() will indeed return all types, it does not necessarily mean you could activate them and could thus potentially throw a ReflectionTypeLoadException.
A classic example for not being able to activate a type would be when the type returned is derived from base but base is defined in a different assembly from that of derived, an assembly that the calling assembly does not reference.
So say we have:
Class A // in AssemblyA
Class B : Class A, IMyInterface // in AssemblyB
Class C // in AssemblyC which references AssemblyB but not AssemblyA
If in ClassC which is in AssemblyC we then do something as per accepted answer:
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
Then it will throw a ReflectionTypeLoadException.
This is because without a reference to AssemblyA in AssemblyC you would not be able to:
var bType = typeof(ClassB);
var bClass = (ClassB)Activator.CreateInstance(bType);
In other words ClassB is not loadable which is something that the call to GetTypes checks and throws on.
So to safely qualify the result set for loadable types then as per this Phil Haacked article Get All Types in an Assembly and Jon Skeet code you would instead do something like:
public static class TypeLoaderExtensions {
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) {
if (assembly == null) throw new ArgumentNullException("assembly");
try {
return assembly.GetTypes();
} catch (ReflectionTypeLoadException e) {
return e.Types.Where(t => t != null);
}
}
}
And then:
private IEnumerable<Type> GetTypesWithInterface(Assembly asm) {
var it = typeof (IMyInterface);
return asm.GetLoadableTypes().Where(it.IsAssignableFrom).ToList();
}
To find all types in an assembly that implement IFoo interface:
var results = from type in someAssembly.GetTypes()
where typeof(IFoo).IsAssignableFrom(type)
select type;
Note that Ryan Rinaldi's suggestion was incorrect. It will return 0 types. You cannot write
where type is IFoo
because type is a System.Type instance, and will never be of type IFoo. Instead, you check to see if IFoo is assignable from the type. That will get your expected results.
Also, Adam Wright's suggestion, which is currently marked as the answer, is incorrect as well, and for the same reason. At runtime, you'll see 0 types come back, because all System.Type instances weren't IFoo implementors.
Other answers here use IsAssignableFrom. You can also use FindInterfaces from the System namespace, as described here.
Here's an example that checks all assemblies in the currently executing assembly's folder, looking for classes that implement a certain interface (avoiding LINQ for clarity).
static void Main() {
const string qualifiedInterfaceName = "Interfaces.IMyInterface";
var interfaceFilter = new TypeFilter(InterfaceFilter);
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var di = new DirectoryInfo(path);
foreach (var file in di.GetFiles("*.dll")) {
try {
var nextAssembly = Assembly.ReflectionOnlyLoadFrom(file.FullName);
foreach (var type in nextAssembly.GetTypes()) {
var myInterfaces = type.FindInterfaces(interfaceFilter, qualifiedInterfaceName);
if (myInterfaces.Length > 0) {
// This class implements the interface
}
}
} catch (BadImageFormatException) {
// Not a .net assembly - ignore
}
}
}
public static bool InterfaceFilter(Type typeObj, Object criteriaObj) {
return typeObj.ToString() == criteriaObj.ToString();
}
You can set up a list of interfaces if you want to match more than one.
loop through all loaded assemblies, loop through all their types, and check if they implement the interface.
something like:
Type ti = typeof(IYourInterface);
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {
foreach (Type t in asm.GetTypes()) {
if (ti.IsAssignableFrom(t)) {
// here's your type in t
}
}
}
This worked for me (if you wish you could exclude system types in the lookup):
Type lookupType = typeof (IMenuItem);
IEnumerable<Type> lookupTypes = GetType().Assembly.GetTypes().Where(
t => lookupType.IsAssignableFrom(t) && !t.IsInterface);
I see so many overcomplicated answers here and people always tell me that I tend to overcomplicate things. Also using IsAssignableFrom method for the purpose of solving OP problem is wrong!
Here is my example, it selects all assemblies from the app domain, then it takes flat list of all available types and checks every single type's list of interfaces for match:
public static IEnumerable<Type> GetImplementingTypes(this Type itype)
=> AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes())
.Where(t => t.GetInterfaces().Contains(itype));
Other answer were not working with a generic interface.
This one does, just replace typeof(ISomeInterface) by typeof (T).
List<string> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())
.Where(x => typeof(ISomeInterface).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
.Select(x => x.Name).ToList();
So with
AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())
we get all the assemblies
!x.IsInterface && !x.IsAbstract
is used to exclude the interface and abstract ones and
.Select(x => x.Name).ToList();
to have them in a list.
All the answers posted thus far either take too few or too many assemblies into account. You need to only inspect the assemblies that reference the assembly containing the interface. This minimizes the number of static constructors being run unnecessarily and save a huge amount of time and possibly unexpected side effects in the case of third party assemblies.
public static class ReflectionUtils
{
public static bool DoesTypeSupportInterface(Type type, Type inter)
{
if (inter.IsAssignableFrom(type))
return true;
if (type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == inter))
return true;
return false;
}
public static IEnumerable<Assembly> GetReferencingAssemblies(Assembly assembly)
{
return AppDomain
.CurrentDomain
.GetAssemblies().Where(asm => asm.GetReferencedAssemblies().Any(asmName => AssemblyName.ReferenceMatchesDefinition(asmName, assembly.GetName())));
}
public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)
{
var assembliesToSearch = new Assembly[] { desiredType.Assembly }
.Concat(GetReferencingAssemblies(desiredType.Assembly));
return assembliesToSearch.SelectMany(assembly => assembly.GetTypes())
.Where(type => DoesTypeSupportInterface(type, desiredType));
}
public static IEnumerable<Type> NonAbstractTypesImplementingInterface(Type desiredType)
{
return TypesImplementingInterface(desiredType).Where(t => !t.IsAbstract);
}
}
Edit: I've just seen the edit to clarify that the original question was for the reduction of iterations / code and that's all well and good as an exercise, but in real-world situations you're going to want the fastest implementation, regardless of how cool the underlying LINQ looks.
Here's my Utils method for iterating through the loaded types. It handles regular classes as well as interfaces, and the excludeSystemTypes option speeds things up hugely if you are looking for implementations in your own / third-party codebase.
public static List<Type> GetSubclassesOf(this Type type, bool excludeSystemTypes) {
List<Type> list = new List<Type>();
IEnumerator enumerator = Thread.GetDomain().GetAssemblies().GetEnumerator();
while (enumerator.MoveNext()) {
try {
Type[] types = ((Assembly) enumerator.Current).GetTypes();
if (!excludeSystemTypes || (excludeSystemTypes && !((Assembly) enumerator.Current).FullName.StartsWith("System."))) {
IEnumerator enumerator2 = types.GetEnumerator();
while (enumerator2.MoveNext()) {
Type current = (Type) enumerator2.Current;
if (type.IsInterface) {
if (current.GetInterface(type.FullName) != null) {
list.Add(current);
}
} else if (current.IsSubclassOf(type)) {
list.Add(current);
}
}
}
} catch {
}
}
return list;
}
It's not pretty, I'll admit.
Even better when choosing the Assembly location. Filter most of the assemblies if you know all your implemented interfaces are within the same Assembly.DefinedTypes.
// We get the assembly through the base class
var baseAssembly = typeof(baseClass).GetTypeInfo().Assembly;
// we filter the defined classes according to the interfaces they implement
var typeList = baseAssembly.DefinedTypes.Where(type => type.ImplementedInterfaces.Any(inter => inter == typeof(IMyInterface))).ToList();
By Can Bilgin
There's no easy way (in terms of performance) to do what you want to do.
Reflection works with assemblys and types mainly so you'll have to get all the types of the assembly and query them for the right interface. Here's an example:
Assembly asm = Assembly.Load("MyAssembly");
Type[] types = asm.GetTypes();
Type[] result = types.where(x => x.GetInterface("IMyInterface") != null);
That will get you all the types that implement the IMyInterface in the Assembly MyAssembly
There are many valid answers already but I'd like to add anther implementation as a Type extension and a list of unit tests to demonstrate different scenarios:
public static class TypeExtensions
{
public static IEnumerable<Type> GetAllTypes(this Type type)
{
var typeInfo = type.GetTypeInfo();
var allTypes = GetAllImplementedTypes(type).Concat(typeInfo.ImplementedInterfaces);
return allTypes;
}
private static IEnumerable<Type> GetAllImplementedTypes(Type type)
{
yield return type;
var typeInfo = type.GetTypeInfo();
var baseType = typeInfo.BaseType;
if (baseType != null)
{
foreach (var foundType in GetAllImplementedTypes(baseType))
{
yield return foundType;
}
}
}
}
This algorithm supports the following scenarios:
public static class GetAllTypesTests
{
public class Given_A_Sample_Standalone_Class_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(SampleStandalone);
_expectedTypes =
new List<Type>
{
typeof(SampleStandalone),
typeof(object)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Abstract_Base_Class_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(SampleBase);
_expectedTypes =
new List<Type>
{
typeof(SampleBase),
typeof(object)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Child_Class_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(SampleChild);
_expectedTypes =
new List<Type>
{
typeof(SampleChild),
typeof(SampleBase),
typeof(object)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Base_Interface_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(ISampleBase);
_expectedTypes =
new List<Type>
{
typeof(ISampleBase)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Child_Interface_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(ISampleChild);
_expectedTypes =
new List<Type>
{
typeof(ISampleBase),
typeof(ISampleChild)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Implementation_Class_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
protected override void Given()
{
_sut = typeof(SampleImplementation);
_expectedTypes =
new List<Type>
{
typeof(SampleImplementation),
typeof(SampleChild),
typeof(SampleBase),
typeof(ISampleChild),
typeof(ISampleBase),
typeof(object)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
public class Given_A_Sample_Interface_Instance_Type_When_Getting_All_Types
: Given_When_Then_Test
{
private Type _sut;
private IEnumerable<Type> _expectedTypes;
private IEnumerable<Type> _result;
class Foo : ISampleChild { }
protected override void Given()
{
var foo = new Foo();
_sut = foo.GetType();
_expectedTypes =
new List<Type>
{
typeof(Foo),
typeof(ISampleChild),
typeof(ISampleBase),
typeof(object)
};
}
protected override void When()
{
_result = _sut.GetAllTypes();
}
[Fact]
public void Then_It_Should_Return_The_Right_Type()
{
_result.Should().BeEquivalentTo(_expectedTypes);
}
}
sealed class SampleStandalone { }
abstract class SampleBase { }
class SampleChild : SampleBase { }
interface ISampleBase { }
interface ISampleChild : ISampleBase { }
class SampleImplementation : SampleChild, ISampleChild { }
}
I got exceptions in the linq-code so I do it this way (without a complicated extension):
private static IList<Type> loadAllImplementingTypes(Type[] interfaces)
{
IList<Type> implementingTypes = new List<Type>();
// find all types
foreach (var interfaceType in interfaces)
foreach (var currentAsm in AppDomain.CurrentDomain.GetAssemblies())
try
{
foreach (var currentType in currentAsm.GetTypes())
if (interfaceType.IsAssignableFrom(currentType) && currentType.IsClass && !currentType.IsAbstract)
implementingTypes.Add(currentType);
}
catch { }
return implementingTypes;
}
OfType Linq method can be used exactly for this kind of scenarios:
https://learn.microsoft.com/fr-fr/dotnet/api/system.linq.enumerable.oftype?view=netframework-4.8
If it helps anyone, this is what I'm using to make some of my unit tests easier :)
public static Type GetInterfacesImplementation(this Type type)
{
return type.Assembly.GetTypes()
.Where(p => type.IsAssignableFrom(p) && !p.IsInterface)
.SingleOrDefault();
}
public IList<T> GetClassByType<T>()
{
return AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.ToList(p => typeof(T)
.IsAssignableFrom(p) && !p.IsAbstract && !p.IsInterface)
.SelectList(c => (T)Activator.CreateInstance(c));
}
You could use some LINQ to get the list:
var types = from type in this.GetType().Assembly.GetTypes()
where type is ISomeInterface
select type;
But really, is that more readable?

Structuremap addalltypesof constructed by a specific constructor

I really like StructureMap as an IOC-framework especially the convention based registration. Now I try to do the following: I want to add all types that implement a specific interface when the class has a default (no parameters) constructor. And the types must be created using this constructor.
This is what I have untill now, which registers the correct types, but how do I specify that the default constructor should be used when creating an instance.
public class MyRegistry : Registry
{
public MyRegistry()
{
Scan(
x =>
{
x.AssemblyContainingType<IUseCase>();
x.Exclude(t => !HasDefaultConstructor(t));
x.AddAllTypesOf<IUseCase>();
});
}
private static bool HasDefaultConstructor(Type type)
{
var _constructors = type.GetConstructors();
return _constructors.Any(c => IsDefaultConstructor(c));
}
private static bool IsDefaultConstructor(ConstructorInfo constructor)
{
return !constructor.GetParameters().Any();
}
}
There are a few ways to force StructureMap to use a specific constructor. The simplest is to put the DefaultConstructor attribute on the constructor you want to use. Assuming you don't want to do that, you would have to create a custom RegistrationConvention.
public class UseCaseRegistrationConvention : IRegistrationConvention
{
public void Process(Type type, Registry registry)
{
if (type.IsAbstract || type.IsInterface || type.IsEnum)
return;
var useCaseInterface = type.GetInterface("IUseCase");
if (useCaseInterface == null)
return;
var constructor = type.GetConstructors().FirstOrDefault(c => !c.GetParameters().Any());
if (constructor != null)
{
registry.For(useCaseInterface).Add(c => constructor.Invoke(new object[0]));
}
}
}
Then use it in your Scan call:
Scan(x =>
{
x.AssemblyContainingType<IUseCase>();
x.With(new UseCaseRegistrationConvention());
});

Categories

Resources