gpt4 book ai didi

c# - IoC 容器不适用于 WebForms

转载 作者:行者123 更新时间:2023-11-30 21:50:47 25 4
gpt4 key购买 nike

我想使用 ASP.NET 网络表单实现 IoC 容器。我完成了这些步骤:

  1. 安装NinjectNinject.Web ddl

  2. 公共(public)类全局:NinjectHttpApplication

  3. 创建内核

    public override IKernel CreateKernel()
    {
    IKernel kernel = new StandardKernel(new Module.Module());
    return kernel;
    }
  4. 创建模块

    public override void Load()
    {
    Bind<IMetricService>().To<MetricService>();
    }
  5. 页面上使用注入(inject)

    public partial class _Default : Page
    {
    [Inject]
    private IMetricService metricService;

    protected void Page_Init(object sender,EventArgs e)
    {
    metricService = new MetricService(metricService);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    metricService.GetAllMetrics();
    }
    }

这是我的 MetricService

 public class MetricService : IMetricService
{
[Inject]
private IMetricService _metricService;

public MetricService(IMetricService metricService)
{
this._metricService = metricService;
}

public void GetAllCriteria()
{
_metricService.GetAllCriteria();
Console.WriteLine("metric service");
}
}

据我所知,当在 MetricService 构造函数中传递 IMetricService 时,IoC 容器必须绑定(bind)此 MetricService 类。我认为我的错误是普遍的,但我不明白在哪里。

最佳答案

您需要将公共(public)属性与 Inject 属性一起使用,以便可以看到它们。此外,不要依赖于 MetricService 类的具体实现。使用该服务的类应仅依赖于抽象实现(接口(interface),在本例中为 IMetricService)。

public partial class _Default : Page
{
[Inject]
public IMetricService metricService { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
metricService.GetAllMetrics();
}
}

而且指标服务不需要它自己的实例。那只是灾难的根源。更改您的 MetricService 类,使其现在无需通过递归调用自身即可检索所有条件。

public class MetricService : IMetricService
{
public void GetAllCriteria()
{
//this is where you call out to your database
//or do whatever else you need to do to return the criteria
}
}

另外,我认为 GetAllCriteria 应该返回一些东西?这通常就是以前缀“get”开头的方法的意思。因此,您需要将返回类型从 void 更改为您要返回的类型。

关于c# - IoC 容器不适用于 WebForms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36154760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com