vendredi 20 mai 2016

C# - Instantiating interface implementation from another assembly the right way

I'm currently developing some kind of "mini SDK" with useful classes and functions I often use.

Therefore I made several interfaces which can be implemented in other assemblies.

So it basically looks like this:

// In SDK.dll:

namespace MySDK
{
    public interface IExample
    {
        /* .. */
    }   
}


// In another assembly:

namespace Example
{
    public class Implementation : MySDK.IExample
    {
        /* .. */
    }
}

This is no problem. My problem is, in the SDK I want to use the actual implementation of this interface, so what I've done is this:

// in SDK.dll

    private IExample GetImplementation(string fileName)
    {
        Type implementation = Assembly
            .LoadFrom(fileName)
            .GetExportedTypes()
            .Where(t =>
                t.GetInterface(typeof(IExample).FullName) != null
                && (t.Attributes & TypeAttributes.Abstract) != TypeAttributes.Abstract)
            .FirstOrDefault();

        if(implementation != null)
        {
            return (IExample)Activator.CreateInstance(implementation);
        }
        else
        {
            return null;
        }
    }

This works and does what I want it to do, but it looks really ugly and somehow wrong.

I'm not sure, is this the right / best way to do this or is there any better way?





Aucun commentaire:

Enregistrer un commentaire