How to check if type in Assembly implements particular Interface
27 July 2017
Hello everybody,
today I want to give sample of reading available types from dll .net assembly, check if at least one of them implements interface, and if implements then to create instance of that type and return it.
So, imagine you have such interface declaration in your code:
public interface ILogger { /// <summary> /// Convert <see cref="LoggerMessage"/> to string based on the formats specified. /// </summary> /// <param name="message">The message to be converted.</param> /// <returns>Converted <paramref name="message"/>.</returns> LoggerMessage Handle(LoggerMessage message); bool Handlable(LoggerMessage message);
}
and following implementation of this interface:
public class LoggerDateTimeAdder : ILogger { public LoggerMessage Handle(LoggerMessage message) { message.AppendAdditionalInfo("start", DateTime.Now); return message; } public bool Handlable(LoggerMessage message) { return true; } }
Then you can use following function in order to read your dll and create instance of LoggerDateTimeAdder:
ILogger LoadFromAssembly(string assmFileName) { ILoggerItemFormatter result = null; var assembly = Assembly.LoadFile(assmFileName); foreach (Type exportedType in assembly.ExportedTypes) { if(typeof(ILogger).IsAssignableFrom(exportedType)) { result = assembly.CreateInstance(exportedType.FullName) as ILogger; break; } } return result; }