Hossein Hagh
Hossein Hagh

Reputation: 127

how to use unit of work pattern in public static

I am Use this code For select 4 Last Record Of Database in various page

public static List<Tour> GetLastTour()
{
    using (var Context = new MvcHghDbContext())
    {
        return (Context.Tours.Take(4).OrderByDescending(x=>x.Titl  e).ToList());
    }
}

How To Use unit of work pattern in static Method in Static Class ? But Static Constructor Erorr! such this code plz help me:

public static class DropDownList{
    private  readonly ICatHotellService _catHotellService;
    private  readonly ICatTourismService _catTourismService;
    private  readonly ICatTourService _catTourService;
    private  readonly IUnitOfWork _uow;
    public DropDownList(ICatHotellService CatHotellService, IUnitOfWork ouw, ICatTourService CatTourService, ICatTourismService CatTourismService)
    {
        _uow=ouw;
        _catHotellService = CatHotellService;
        _catTourismService = CatTourismService;
        _catTourService = CatTourService;`
    }
}

Upvotes: 0

Views: 463

Answers (2)

VahidN
VahidN

Reputation: 19156

  • You are not using UoW at all. UoW means injecting one instance of the MvcHghDbContext to different classes of your service layer during a request call and not instantiating it directly each time such as your GetLastTour method.
  • Don't use static classes in your service layer. extract an interface from them and let the IoC container manage its life time.
  • Also you can use service locator pattern (such as calling ObjectFactory.GetInstance<>) every where even in static classes. It's an anti pattern and should be avoided as much as possible, because now the IoC Container is a dependency in your class.

Upvotes: 1

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

The short answer is that this can't work. Static classes may only have static constructors, and these get called by the runtime when the app is created. Thus, this happens long before your dependency injection has been configured. On top of that, you should never ever ever have static data contexts in a web application, because these are shared by all users of your app, thus two users using the same data context will write over each others data model.

Upvotes: 1

Related Questions