GrahamJRoy
GrahamJRoy

Reputation: 1643

Using static method with IOC data access

I have an MVC project that uses the repository pattern. I am also using Ninject for the IOC containers. I am having a problem though with storing some cached values when the project loads.

In my Global.asax.cs I have:

...(some settings)
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
....
...CustomDataCache.Configure();

and in my ControllerFactory I have the bindings I need:

_ninjectKernal.Bind<IDataContext>().To<DataContext>()
            .WithConstructorArgument("appNamekey", "Name of Data Application")
            .WithConstructorArgument("serverLocationNameKey", "Location of Application Server");

and in my CustomCache class I want to do something like:

private IDataContext _context;

private CustomDataCache(IDataContext context)
    {
        _context = context;
    }

public static void Configure(){
  System.Web.HttpContext.Current.Cache["NDECCategories"] = _context.GetNdecCategories();

I want to call Configure() statically from the global but how do i do this when I need an instance of the DataContext?

Thanks,

Upvotes: 1

Views: 177

Answers (2)

user4573148
user4573148

Reputation:

Resolving dependencies varies. For webforms...

Public Class _Default
    Inherits Page

    <Dependency()>
    Public Property _userService As IUserService

For MVC

public UserController(IDataContextAsync context)

In reality, you shouldn't need to access your datacontext directly from your webapplication. You should be accessing the Service that has the IDataContextAsync setup in your constructor...

Public Class UserService
    Inherits Service(Of User)
    Implements IUserService

    Private ReadOnly _repository As IRepositoryAsync(Of User)

    Public Sub New(repository As IRepositoryAsync(Of User))
        MyBase.New(repository)
        _repository = repository
    End Sub

Upvotes: 1

user6470655
user6470655

Reputation:

Why not pass in the categories as a parameter in your Configure method?

var _context = DependencyResolver.Current.GetService<IDataContext>();
var categories = _context.GetNdecCategories();
CustomDataCache.Configure(categories);

Upvotes: 0

Related Questions