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. 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. 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?
EDIT: To Clarify, What's the best way to use an instance of a repository inside static methods?
Web methods must be static. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.