简体   繁体   中英

c# unity generics interface and abstract class

I have an interface :

public interface IMigrationSchema<T> 
{
    T MapEvent(IOtherEvent sourceEvent);
}

implemented by an abstract class:

public abstract class MigrationSchema<T> : IMigrationSchema<T>
{
    public abstract T MapEvent(IOtherEvent sourceEvent);
}

and then the actual implementation of my MigrationSchema :

public class MigrationSchemaImpl: MigrationSchema<EventAfterMigration>
{
    public MigrationSchemaImpl()
        : base()
    {
    }

    public override EventAfterMigrationMapEvent(IOtherEvent actualSourceEvent)
    {
        return new EventAfterMigration(actualSourceEvent);
    }
}

knowing that:

public class EventAfterMigration : BaseEvent

What I'd like to do ideally:

var migrationSchema = container.Resolve<IMigrationSchema<BaseEvent>>();

and having in my config file:

<register type="IMigrationSchema`1[[MyApp.BaseEvent, MyApp]]" mapTo="MigrationSchemaImpl">

I know this seems abstract, I've tested out a lot of possibilities but everytime I get the InvalidCastException , saying that the

MigrationSchemaImpl cannot be cast to IMigrationSchema1[BaseEvent]

I feel like this is perfectly doable but I'm missing something simple. Any help appreciated !

Relationship between types does not magically become relationship between generic interfaces/types using this types. MigrationSchemaImpl implements IMigrationSchema<EventAfterMigration> , not the IMigrationSchema<BaseEvent> - so you can't cast one to another (with or without Unity).

You'll get the same error with simple code:

var base = (IMigrationSchema<BaseEvent>)
     (new MigrationSchemaImpl());

You may try to use variance like IMigrationSchema<in BaseEvent> (not sure if it will help in your case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM