接口问题C#和依赖项注入

如何解决接口问题C#和依赖项注入

我有问题。让我们来看一个例子: 您获得了将由Employee.cs和Owener.cs实现的接口:

public interface IEmployee
 {
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Location { get; set; }
  }

 public class Employee: IEmployee
 {
     public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Location { get; set; }
}

  public class Owner: IEmployee
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Location { get; set; }

    public string Status{ get; set; } <--- //problem string
}

现在,当我们使用依赖注入时,它返回员工或经理的对象,这就是我遇到问题的地方。

public class EmployeeCheck{

   private IEmployee empObj;

  public EmployeeCheck(IEmployee _em)
  {
     empObj=_em
  }

public void PrintCheck()
 {
   string str=_em.FirstName;
   string str2=(Owner)_emp.Status <--- //problem...how do I access it?? It can't be accessed cause 
                                       //IEMployee doesn't have status field!
  }

因此,基本上,如果我使用IEmployee作为接口,则无法访问新的Owner类中的字段,并且如果确实将它们放在接口中,则不需要实现它的Employee类将被强制执行实现不需要的东西!而且由于DI注入或其他设计模式,我确实需要IEmployee


好的,我不能使用抽象类...所以让我们讨论更多有关IStatus解决方案的信息...所以您正在谈论编写这样的代码:

public interface IStatus:IEmployee
{
    public string Title { get; set; }
}

公共类所有者:IEmployee,IStatus { 公共字符串FirstName {get;组; }

public string LastName { get; set; }

public string Location { get; set; }

public string Status{ get; set; } <--- //problem string

}

但是我该如何在“员工检查”类中使用它?

公共类EmployeeCheck {

   private IEmployee empObj;

  public EmployeeCheck(IEmployee _em,IStatus)
  {
 empObj=_em
  }

}

解决方法

这取决于您如何使用或为什么必须使用依赖项注入。我认为在这些情况下,根据您的示例,使用它并不是很好,因为它使您变得简单一些。

如果要使用“状态”值执行操作,则可以通过生成一个新界面来隔离界面。像这样。 def MyCallback(a,b): # custom function print(a,b) def SomeEventHandler(f): # parameter is reference to another function f(1,2) # call passed in function,it must have these parameters SomeEventHandler(MyCallback) # pass custom function to handler ,然后您仅在所有者和构造函数EmployeeCheck中实现此接口,就注入了public interface IStatus { string Status { get; set; } }

但是,如果没有必要,为什么不使用IEmployee,则可以将其作为抽象类来完成。

IStatus
,

您通常可以使用IoC Containers(例如StructureMap或Unity)来处理您要处理的场景,方法是使用命名实例。这些容器提供了开箱即用的这种功能。

可以在.NET Core中以多种方式实现相同的目的。一种方法是使用IServiceCollection中的扩展方法。下面的代码段将指导您逐步了解如何在您的情况下完成此操作

// using Microsoft.Extensions.DependencyInjection
// Startup.cs - ConfigureServices()
services.AddTransient(serviceProvider =>
{
    Func<string,IMyClass> func = key =>
    {
        switch (key)
        {
            case "MyClass":
                return serviceProvider.GetService<MyClass>();
            case "MyClass1":
                return serviceProvider.GetService<MyClass2>();
            default:
                throw new KeyNotFoundException();
        }
    };
    return func;
});

//Register your services here as usual
services.AddTransient<IMyClass,MyClass>();
services.AddTransient<IMyClass,MyClass2>();

您实际上是在这里创建一个工厂,该工厂将基于key给出所需类型的依赖关系。以下代码段显示了如何在控制器中完成此操作。

// ctor of your controller
public MyController(Func<string,IMyClass> injector)
{
    // key here could be 'MyClass' or 'MyClass2'
    IMyClass service = injector("<key>");
}

下面是我为上述示例考虑的示例类别的结构

// implementation 1
public class MyClass : IMyClass
{
}

// implementation 2
public class MyClass2 : IMyClass
{
}

// interface
public interface IMyClass
{
}

还有其他方法可以处理此问题。您可以查看this的其他方法的答案。

,

您需要考虑的第一个问题是:EmployeeCheck在用Employee实例化(例如)时应该做什么?因为它似乎需要Status才能打印支票?

接口背后的全部想法是,它们为可以用对象执行的操作提供了约定。在这种情况下,您正在尝试执行合同中未指定的操作(使用Status),因此类型系统使操作变得更加困难(强制您强制转换)。

一个避免转换的选项(由@Diegorincon建议)是创建另一个实现IHasStatus的接口(类似IEmployee),然后在EmployeeCheck中更改类型({ {1}}可能更清晰?)到CheckPrinter

IEmployeeWithStatus

如果您在示例中使用签名而感到困惑,那么编写代码的一种选择是使用类型模式来编写switch语句:

interface IEmployee
{
     string FirstName { get; }
     string LastName { get; }
    
}
interface IEmployeeWithStatus:IEmployee
{
    string Status { get; }
}
public class Owner : IEmployeeWithStatus
{
    public string FirstName { get; }
    public string LastName { get; }
    public string Status { get; }
}
class EmployeeCheck
{
    private readonly IEmployeeWithStatus _employeeWithStatus;
    public EmployeeCheck(IEmployeeWithStatus employeeWithStatus)
    {
        _employeeWithStatus = employeeWithStatus;
    }

    void PrintCheck()
    {
        // no casting needed
        Console.Write($"{_employeeWithStatus.FirstName} {_employeeWithStatus.LastName} {_employeeWithStatus.Status}");
    }
}

它比必须在整个地方投射都要干净,但是到了最后,它只是解决了同样的问题。

(在面向对象的范例中,这种情况在所有情况下都会出现,在这种情况下,当您手头有一个更通用的类型(例如 switch (employee) { case Owner owner: { // you can use owner.Status here Console.WriteLine(owner.Status); } break; case Employee employee: { // hmm..,now what?! } break; } 之类的对象)时,却发现自己想要可以根据其特定类型(例如Animal进行操作。按照上面的代码打开类型通常被认为是代码异味。更多细节,我也许可以提出其他想法)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-