How to check if type in Assembly implements particular Interface
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; }
Ready to take your Acumatica development to the next level? Just like dynamically loading and instantiating types from a .NET assembly, your business might need custom solutions tailored to your unique workflows. Whether it's enhancing logging mechanisms, integrating third-party tools, or building entirely new features, our team is here to help.
Leave a customization request today and let us create a solution that fits your needs as seamlessly as the LoggerDateTimeAdder integrates with your logging system. Don’t settle for out-of-the-box—let’s build something extraordinary together!