ASP.net MVC Controller - Constructor usage

前端 未结 2 1420
面向向阳花
面向向阳花 2021-01-30 01:45

I\'m working on an ASP.net MVC application and I have a question about using constructors for my controllers.

I\'m using Entity Framework and linq to Entities for all o

2条回答
  •  执念已碎
    2021-01-30 02:23

    You are asking the right questions.

    A. It is definitely not appropriate to create this dependencies inside each action method. One of the main features of MVC is the ability to separate concerns. By loading up your controller with these dependencies, you are making the controller for thick. These should be injected into the controller. There are various options for dependency injection (DI). Generally these types of objects can be either injected into the constructor or into a property. My preference is constructor injection.

    B. The lifetime of these objects will be determined by the garbage collector. GC is not deterministic. So if you have objects that have connections to resource constrained services (database connections) then you may need to be sure you close those connections your self (instead of relying on dispose). Many times the 'lifetime' concerns are separated out into an inversion of control (IOC) container. There are many out there. My preference is Ninject.

    C. The instantiation costs are probably minimal. The database transactions cost are where you probably want to focus your attention. There is a concept called 'unit of work' you may want to look into. Essentially, a database can handle transactions larger than just one save/update operation. Increasing the transaction size can lead to better db performance.

    Hope that gets you started.

提交回复
热议问题