【问题标题】:Trying to create Interface with a method that uses a dynamic or anonymous type but an implementation that uses another尝试使用使用动态或匿名类型的方法但使用另一种实现的方法创建接口
【发布时间】:2017-08-05 05:38:33
【问题描述】:

我正在尝试在 ASP.NET MVC 中执行此操作。我想要一个界面

public interface IMyInterface
{
    Task<IReadOnlyCollection<SomeTypeDTO>> aAssembleResponse(dynamic aSomeContext);
}

在我的实现中,我想要以下内容:

public class MyInterfaceService
{
    .... //unneeded code
    public async Task<IReadOnlyCollection<SomeTypeDTO>> aAssembleResponse(
        SomeContext aSomeContext)
        return whatever     
}

我在界面中使用 dynamic 进行初始化,但我期待另一种类型(在本例中为 SomeContext)。我的公司在 DI 上真的很厉害,我真的在这里碰壁了。我不能 new 增加 SomeContext - 也不能在这里使用构造函数注入方法。如果我只是将其保留为 dynamic 它绝对可以正常工作 - 但 Autofac 发疯了并拒绝通过它。

【问题讨论】:

  • 你是设计IMyInterface 还是强加给你的。在这里使用dynamic 听起来可能是一个非常糟糕的选择。
  • 听起来你在找generic interface.
  • Scott,动态的使用只是一个技巧。这就是我在这里的原因 - 我知道它很臭。
  • 好的,如果我用泛型实现它,这就是交易,例如: aAssembleResponse(SomeContext aSomeContext) 变为 aAssembleResponse(T aSomeContext) 一切正常,直到我尝试访问内部的 DbSet aSomeContext 或将其转换为 SomeContext。到目前为止,我已经尝试过 Convert.ChangeType,有什么建议吗?

标签: c# asp.net-mvc dependency-injection interface autofac


【解决方案1】:

好的,所以我想出了解决方案,我只能责怪我正在克服的流感。但这是解决这个问题的非常简单的方法。

public interface IMyInterface
{
        Task<IReadOnlyCollection<SomeTypeDTO>> aAssembleResponse<T>(T aSomeContext);
}

然后是我的实现

public async Task<IReadOnlyCollection<SomeTypeDTO>> aAssembleResponse<T>(T aSomeContext)
{
    var _SomeContext = (SomeContext)Convert.ChangeType(aSomeContext, typeof(SomeContext));
    return _SomeContext;     
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多