简体   繁体   English

在webforms aspx.cs文件ASP.NET Web表单中使用存储库类的正确方法

[英]Proper way to use a repository class in an webforms aspx.cs file ASP.NET Web forms

What's the proper way to instantiate an instance of a repository class in a code behind file in ASP.NET Web forms aspx.cs file. 在ASP.NET Web窗体的aspx.cs文件中,在代码隐藏文件中实例化存储库类的实例的正确方法是什么。 I've tried doing it the same way that you'd do it in a MVC Controller but it seems like I'm missing out on something. 我试过这样做就像你在MVC控制器中那样做,但似乎我错过了一些东西。 This is what I've tried so far with no luck. 这是我到目前为止没有运气的尝试。

public partial class Ajax : System.Web.UI.Page
{
    private Repository _repo;

    public Ajax()
    {
        _repo = new Repository();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [System.Web.Services.WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string CreateForm(object data)
    {
        _repo.Insert(data);
    }
}

public class Repository()
{
    public void Insert(object data)
    {
         //do something.
    }
}

The problem is that visual studio gives me the following error when I try to build it: "An object reference is required for the non-static field, method, or property Ajax._repo" What's the proper way to give static webmethod access to an instance of the Repository class? 问题是当我尝试构建它时,visual studio给我以下错误:“非静态字段,方法或属性Ajax._repo需要一个对象引用”什么是给静态webmethod访问的正确方法Repository类的实例?

EDIT: To Clarify, What's the best way to use an instance of a repository inside static methods? 编辑:要澄清,在静态方法中使用存储库实例的最佳方法是什么?

Web methods must be static. Web方法必须是静态的。 They can't access instance members. 他们无法访问实例成员。 You can just grab the repository within your static method. 您可以在静态方法中获取存储库。

[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string CreateForm(object data)
{
    Repository repo = new Repository();
    repo.Insert(data);
}

Or better yet, abandon WebMethod and instead start making use of Web API in your project, utilize Dependency Injection. 或者更好的是,放弃WebMethod,而是开始在项目中使用Web API ,使用依赖注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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