Sherry8212
Sherry8212

Reputation: 77

MVC, Entity Framework DBContext connection in Global.asax

I'm using Entity Framework and Dependency Injection. To get database results in a controller, I'm doing:-

    private IJobSeekerRepository repository;

    public JobseekersController(IJobSeekerRepository Repository)
    {
        repository = Repository;
    }

then doing something like.....

     return View(repository.GetAllJobSeekers);

I'm trying to follow a tutorial where you can set the Thread.CurrentPrinciple in the Global.asax file, from the database. I've been trying for hours now to get the records from the database into the global file.

How can I set a constructor similar to the 'public JobseekersController' above?

This is what I have, but its throwing an error on 'repository.GetJobSeekersRoles' - Object reference not set to an instance of an object

    public IJobSeekerRepository repository;

    void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated)
        {
            var ctx = HttpContext.Current;

               string[] roles = repository.GetJobSeekersRoles(ctx.User.Identity.Name);
               var newUser = new GenericPrincipal(ctx.User.Identity, roles);
               ctx.User = Thread.CurrentPrincipal = newUser;
        }
    }

Upvotes: 2

Views: 1476

Answers (1)

Martin
Martin

Reputation: 11041

Just use the DependencyResolver object (msdn), as it's built into MVC:

var repository = DependencyResolver.Current.GetService<IJobSeekerRepository>();

Assuming you are setting the DependencyResolver on your app start.

Upvotes: 2

Related Questions