Click here to Skip to main content
15,887,990 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello Friends,

I have one issue to access instance of service on static webmethod to call qjeruy ajax method. I have enitity code first approch and
generic repository pattern implemented in the project.

Following are the code structure.

Repository Class:
C#
public partial class EfRepository<T> : IRepository<T> where T : BaseEntity, new()
{
        private readonly IDbContext _context;
        private IDbSet<T> _entities;
        public EfRepository(IDbContext context)
        {
            this._context = context;
        }

        public T GetById(object id)
        {
            return this.Entities.Find(id);
        }
	//Other methods implemented here
}

Services Class:
C#
public partial class UserService : IUserService
{
        private IRepository<User> repositoryUser;
	public UserService(IRepository<User> _repositoryUser)
        {
            repositoryUser = _repositoryUser;
        }
	//Methods implemented here.
}

Global Application:
C#
void Application_Start(object sender, EventArgs e)
{
	Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();
	builder.Register<IDbContext>(c => new DBObjectContext(ConnectionString)).InstancePerHttpRequest();
	builder.RegisterType<UserService>().As<IUserService>().InstancePerHttpRequest();
	builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
        _containerProvider = new ContainerProvider(builder.Build());      
}


userList.aspx.cs class

C#
public IUserService userService { get; set; } // object created when page is loaded.


Now My requirement is how to access this object in static webmethod which is called through jquery ajax method.

C#
[WebMethod]
public static string MyMethod()
{
	//I want to access userService object here.
}


1. If I can mark object as static then object is not created on load,

I did following trick which is working fine but exception thrown as DbContext is disposed.

I created static object as well.
C#
protected static IUserService userStaticService { get; set; }


and on page load event of page, I assign object to static object.

C#
protected void Page_Load(object sender, EventArgs e)
{
	userStaticService = userService;
}    


and I can access all methods in static web method by using static service object but as I told DBContext is disposed exception is thrown.

Is there any work around to achive my goal? I thinking to create webservice class in class library and write all webmethod withing in that class
which are not static method so I can easily create an object of service interface.

Any guide or tutorial would be greatly appreciate.
Posted
Updated 3-Mar-14 19:02pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900