开发者

C# Dependency Injection Cast Issue

开发者 https://www.devze.com 2023-01-05 12:39 出处:网络
I have several classes that implemen开发者_如何学编程t the same interface. interface IBidManager<E> where E : IEntity

I have several classes that implemen开发者_如何学编程t the same interface.

interface IBidManager<E> where E : IEntity

public class BidManager : IBidManager<EntityObject1>
public class BidManager2 : IBidManager<EntityObject2>
public class BidManager3 : IBidManager<EntityObject3>

In my business manager class I have:

public class BusinessManager : ManagerBase
{
    private IBidManager<IEntity> _bidLogicManager;
    ...

In the BusinessManager is a function I call to change the _bidLogicManager (MyType is an enum)

public void SetLogic(MyType auctionType)
{
    switch (MyType)
    {
        case AuctionType.Classic:
            _bidLogicManager = (IBidManager<IEntity>)new BidManager();
            break;
  ...

IEntity is a blank interface that I use with my POCO classes generated by a t4 and the Entity framework.

I could have swore this was working, but I tried it again and its throwing error sayng:

Unable to cast object of type 'BLL.MyManagers.BidManager' to type 'BLL.BidManagers.IBidManager`1[Entities.IEntity]'.

When I remove (IBidManager) visual studio tells me that an explicit conversion exists... but what is it?

I do not want to define the type when creating the BusinessManager class like so:

public class BusinessManager<E> : ManagerBase where E : class, IEntity
{
      IBidManager<E> _bidLogicManager;

Also, I cannot create a function in the Business manager that takes a IBidManager<E> argument since this is a n-layer asp.net app and I do not want the UI layer knowing anything about the IBidManager


If you can use .Net 4.0, you can solve your cast problem via covariance.

interface IBidManager<out E> where E : IEntity.
0

精彩评论

暂无评论...
验证码 换一张
取 消