How do I inject logging into my EF based partial model class? - asp.net-mvc

I'm using the Nuget downloads of Ninject 3.x & NLog 2.x. I've gotten ILogger working via constructor injection on my controller classes, but I don't know how to make it work within my model classes. My model is a partial class tied to a class generated by ADO.NET EntityObject Generator.
I've tried Property Injection with and without the [Inject] attribute, but it always comes back null. I'm not sure what I need to do as the controller constructor injection was all automatic.
Ultimately I think I'd like to move my Models into their own library so they can be reused, but for now I'd be happy with any answer (even specific to asp.net mvc 3 projects) to get this working.

Looks like EF doesn't really allow IoC to be used for creating models, at least without modifying their T4 template. One suggestion I can give is to use ObjectMaterialized event of your ObjectContext like this:
partial void OnContextCreated()
{
ObjectMaterialized += BAEntities_ObjectMaterialized;
}
public void BAEntities_ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
{
if (e.Entity is MyEntityWithLogging)
{
//apply initialization logic here
((MyEntityWithLogging)e.Entity).Logger = kernel.Get<ILogger>();
}
}

Entities shouldn't have any dependencies. Therefore they should't be created by the IoC container. Rethink your design so that business logic isn't in your entities anymore.

Related

How to share a DbCOntext in n-tier repository pattern. Asp .net mvc

Firstly i must say, i know their is a very close question i found on stackoverflow, but my question is a little different.
I have n-tier application in asp .net mvc, in which I have: A BOL project(which has EF classes and db object etc), BLL project(which has buiseness logic), than we have DAL project(which has db interaction logic, and it uses EF dbcontext from BOL). And a main mvc project which ahs controllers and views etc.
Now, we are using repository pattern, we have many Repositories in BLL with their interfaces. And also we have many repositories in DAL which are without interfaces though. But all of those DAL repositories have one DbContext member in them, which is being created in their constructors, so each DAL repository is interacting with separate instance of DbContext which it has created.
And in our main mvc project, we have used ninject to inject BLL repositories in controllers constructors (in request scope). Now, the issue we are facing is, that each BLL repository has references to one or more DAL repositories, and each of those DAL repositories are using their own seperate DbCOntext. Which is wrong and bad, thats why i am looking for the way to share one DbCOntext in all DAL repositories, per request(No matter how many BLL repositories ninject injects in my controller, just make sure only one DbContext instance is being created and used per request). And dispose that context after each request.
One way i thought was to not create DBcontext in constructor of DAL repositories. But have some method call(say initiateDbContext) for that, than also add this method in BLL repositories, which do nothing but to call the smae method of their member DAL repositories. Call that method for one BLL repository in controller constructor, and than have a method to get and set db contexts in all other repositories from the first repository. But i know this is bad approach, firstly we are creating DbContext in controller, which should be in DAL only, secondly i am adding create, get and set DbCOntext methods in DAL as well as in BLL repositories, because i need to pass DbCOntext to BLL which will pass that to the DAL repositories it communicates with internally. And that's very bad.
That's why i am asking here for any good pattern to achieve "ONE DBCONTEXT PER REQUEST IN N-TIER WITH REPOSITORY PATTERN."
If you are using dependency injection, you should use it all the way, not only in the controllers.
That means, the DBContext should be injected into the Repositories, and Ninject should be configured to resolve your DBContext with per request lifetime.
Based on the answer from #atika i searched further and implemented what he suggested(using ninject/DI in whole application rather than just in one main project of mvc) and it solved the issue, i am posting this answer to add more details and some extra issues i faced and i got to spend time googling about further, so others might save some time.
Idea is to use dependency injection throughout the solution, no matter how many projects/tiers you have in it and no matter how many repositories you have got.
So, the issue comes to the point, that if we want to use ninject or any other DI for binding all dependencies from all tiers/projects, we should have reference to all of those tiers/projects in our main mvc project, so that we can bind the dependencies in NinjectWebCommons, but this will kill the whole purpose of n-tier architecture. We don't want to do that, we want our hierarchy to sustain, like in my case
MainMVCProject->BLL->DLL->DB
So, for this, i found a very helpful article Ninject with N-Tier MVC Application - Inject Object in Business Layer.(Their are also some other approaches, one is to make a project just for bindings and add use that project to bind all dependencies, but that sounds like over engineering and overkill)
Based on which i added the following class in my BLL tier/project(after installing ninject in this project and DAL project too), which has bindings for DLL classes.
using BLL.Repositories;
using BLL.RepositoryInterfaces;
using Ninject.Modules;
using Ninject.Web.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using BOL;
namespace BLL
{
public class LayerBindings : NinjectModule
{
public override void Load()
{//add all references here like these
Bind<AdDb>().ToSelf().InRequestScope();
Bind<db_Entities>().ToSelf().InRequestScope().WithConstructorArgument("ConnectionString", BOL.CommonFunctionsBOL.ConnectionString);
}
}
}
Getting some help from howto-ninject-part-1-basics article, i managed to do many things with ninject, and used many of its features.
Now, you can see i added the bindings of DLL project in this class, which were not accessible in main mvc project. Now, i just need to load these bindings in main ninject.
Now, in NinjectWebCommons.cs file, i added following lines:
//old bindings of BLL and local project.
kernel.Bind<IUserRepository>().To<UserRepository>().InRequestScope();
//now here we bind other dependencies of DAL etc using class we added in BLL
var modules = new List<INinjectModule>
{
new BLL.LayerBindings()
};
kernel.Load(modules);
(In RegisterServices method, after local bindings and BLL objects bindings.)
After doing just this, ninject started working in all the projects and i just used constructor injection or on some places, property injections and all worked fine.
PS1: I also used property injection*(i read that this is not recommended to use property injections, use them only where you cant use constructor injections.)* for private properties and they had to be enabled with kernel.Settings.InjectNonPublic = true; line in "CreateKernel" method before returning the kernal.
Now my property injection is working for private properties too, like this:
[Ninject.Inject]
private SomeDALObject db { get; set; }
PS2: I also installed ninject.web.webapi nuget package for ninject to work with webapis, and also found this line to get an object anywhere from ninject.(I don't know if this is a good way or not, but it does return a fully constructed object which i used than. If any one can clarify or correct me if using this is right or not, that will be great.)
((TypeOfObjectYouWant)System.Web.Mvc.DependencyResolver.Current.GetService(typeof(TypeOfObjectYouWant))).DoSomething();
I hope this might help some people like me looking for proper guide on this issue.
You can write one BaseRepository and implement BaseRepository in all repository classes.
public class BaseRepository
{
public StudentEntities dbStudentEntity;
public BaseRepository()
{
dbStudentEntity = new StudentEntities();
}
}
DataRepository :
public class CurrencyData : BaseRepository,ICurrencyData
{
public List<Models.Currency> GetCurrencyList()
{
var objCurrencies = dbStudentEntity.Currencies.ToList();
List<Models.Currency> currencyList = new List<Models.Currency>();
foreach (var item in objCurrencies)
{
var model = new Models.Currency { CurrencyId = item.CurrencyId, Currency1 = item.Currency1,Code = item.Code,Symbol = item.Symbol,Country = item.Country };
currencyList.Add(model);
}
return currencyList;
}
}

What is the best way to instantiate and dispose DbContext in MVC?

MVC 3 + EF 4.1
I'm choosing between two approaches to deal with DbContext:
Instantiate in Application_BeginRequest, put it into
HttpContext.Current.Items and dispose in Application_EndRequest.
Create disposable UnitOfWork (kindof wrapper for DbContext) and
start each controller action with using(var unitOfWork = new
UnitOfWork()) { ... }
Share your experience please: Which one would you prefer? what are pros and cons for each approach?
I would suggest you use a Dependency Injection framework. You can register your DbContext as per request
container.RegisterType<MyDbContext>().InstancePerHttpRequest();
And inject it as a constructor parameter to the controller.
public class MyController : Controller
{
public MyController(MyDbContext myDbContext)
{
_myDbContext = myDbContext;
}
}
If the registered type implements IDisposable then the DI framework will dispose it when the request ends.
1st approach: It is much more cleaner to use ID framework than manually implementing it. Further all your requests may not need your UoW.
2nd approach: The controller should not know how to construct your UoW(DbContext). Purpose is not reduce the coupling between components.
We currently use repositories injected with UoW (unit of work) instantiated via service locator from an repository factory. Unity controls the lifetime this way taking the work away from you.
Your particular implementation will vary depending if your using POCO's, Entity Objects, etc..
Ultimately you want UoW if your going to be working with more than one objectset in your controller to ensure your just using one context. This will keep your transactions in check etc.
If your going to use multiple objectcontexts (ie. multiple EDMX's), you'll want to look at using UoW with MSDTC...but thats probably more than you wanted to know. In the end, the important thing is to ensure you just instantiate what you need for the controller action (i.e. one instance of the context.). I don't think I'd go with Begin_Request, you may not even need the context for every request.
Don't put DbContext in global.asax! :
Static field of DbContext in Global.asax versus instance field of DbContext in controller class?
Entity framework context as static

DDD and constructor explosion

I'm practicing DDD with ASP.NET MVC and come to a situation where my controllers have many dependencies on different services and repositories, and testing becomes very tedious.
In general, I have a service or repository for each aggregate root. Consider a page which will list a customer, along with it's orders and a dropdown of different packages and sellers. All of those types are aggregate roots. For this to work, I need a CustomerService, OrderService, PackageRepository and a UserRepository. Like this:
public class OrderController {
public OrderController(Customerservice customerService,
OrderService orderService, Repository<Package> packageRepository,
Repository<User> userRepository)
{
_customerService = customerService
..
}
}
Imagine the number of dependencies and constructor parameters required to render a more complex view.
Maybe I'm approaching my service layer wrong; I could have a CustomerService which takes care of all this, but my service constructor will then explode. I think I'm violating SRP too much.
I think I'm violating SRP too much.
Bingo.
I find that using a command processing layer makes my applications architecture cleaner and more consistent.
Basically, each service method becomes a command handler class (and the method parameters become a command class), and every query is also its own class.
This won't actually reduce your dependencies - your query will likely still require those same couple of services and repositories to provide the correct data; however, when using an IoC framework like Ninject or Spring it won't matter because they will inject what is needed up the whole chain - and testing should be much easier as a dependency on a specific query is easier to fill and test than a dependency on a service class with many marginally related methods.
Also, now the relationship between the Controller and its dependencies is clear, logic has been removed from the Controller, and the query and command classes are more focused on their individual responsibilities.
Yes, this does cause a bit of an explosion of classes and files. Employing proper Object Oriented Programming will tend to do that. But, frankly, what's easier to find/organize/manage - a function in a file of dozens of other semi-related functions or a single file in a directory of dozens of semi-related files. I think that latter hands down.
Code Better had a blog post recently that nearly matches my preferred way of organizing controllers and commands in an MVC app.
Well you can solve this issue easily by using the RenderAction. Just create separate controllers or introduce child actions in those controllers. Now in the main view call render actions with the required parameters. This will give you a nice composite view.
Why not have a service for this scenario to return a view model for you? That way you only have one dependency in the controller although your service may have the separate dependencies
the book dependency injection in .net suggests introducing "facade services" where you'd group related services together then inject the facade instead if you feel like you have too many constructor parameters.
Update: I finally had some available time, so I ended up finally creating an implementation for what I was talking about in my post below. My implementation is:
public class WindsorServiceFactory : IServiceFactory
{
protected IWindsorContainer _container;
public WindsorServiceFactory(IWindsorContainer windsorContainer)
{
_container = windsorContainer;
}
public ServiceType GetService<ServiceType>() where ServiceType : class
{
// Use windsor to resolve the service class. If the dependency can't be resolved throw an exception
try { return _container.Resolve<ServiceType>(); }
catch (ComponentNotFoundException) { throw new ServiceNotFoundException(typeof(ServiceType)); }
}
}
All that is needed now is to pass my IServiceFactory into my controller constructors, and I am now able to keep my constructors clean while still allowing easy (and flexible) unit tests. More details can be found at my blog blog if you are interested.
I have noticed the same issue creeping up in my MVC app, and your question got me thinking of how I want to handle this. As I'm using a command and query approach (where each action or query is a separate service class) my controllers are already getting out of hand, and will probably be even worse later on.
After thinking about this I think the route I am going to look at going is to create a SerivceFactory class, which would look like:
public class ServiceFactory
{
public ServiceFactory( UserService userService, CustomerService customerService, etc...)
{
// Code to set private service references here
}
public T GetService<T>(Type serviceType) where T : IService
{
// Determine if serviceType is a valid service type,
// and return the instantiated version of that service class
// otherwise throw error
}
}
Note that I wrote this up in Notepad++ off hand so I am pretty sure I got the generics part of the GetService method syntactically wrong , but that's the general idea. So then your controller will end up looking like this:
public class OrderController {
public OrderController(ServiceFactory factory) {
_factory = factory;
}
}
You would then have IoC instantiate your ServiceFactory instance, and everything should work as expected.
The good part about this is that if you realize that you have to use the ProductService class in your controller, you don't have to mess with controller's constructor at all, you only have to just call _factory.GetService() for your intended service in the action method.
Finally, this approach allows you to still mock services out (one of the big reasons for using IoC and passing them straight into the controller's constructor) by just creating a new ServiceFactory in your test code with the mocked services passed in (the rest left as null).
I think this will keep a good balance out the best world of flexibility and testability, and keeps service instantiation in one spot.
After typing this all out I'm actually excited to go home and implement this in my app :)

Architecting medium size asp mvc - using ninject and creating objects

I'm designing medium-size website using asp.net mvc technology.
All business logic is organized into IServices (like IDomainService, IUserService, IAuthService, ITrainingService). All services are using IRepositories.
I'm using Ninject 1.5 to wire services with controllers and it seems working perfectly.
There is so far one subject I have no idea how to handle. Some services create contexts (per request) - for instance IDomainService creates DomainContext (per request) which is needed for IUserService.
ITrainingService is used only in TrainingController, which is accessible only by authorized users, and ITrainingService requires UserContext (also per request) to know who is having training.
This is my first project using IoC container.
Is there any design pattern or code-schema how to solve it?
I think I can fill context object using ActionFilters but how to manage their lifetime and where to put them to be accessible for IServices? (in an ellegant way)
I've used Ninject specifically in an MVC application. The way you'd accomplish this with Ninject is in the configuration or binding of your dependencies. When you do this, you specify how you want your object lifetimes to be managed. In most cases of a web app, you objects will be per request as you've indicated in your question.
One thing I've noticed in your question is that your DomainContext is being created by an IDomainService object and is used by other objects. If the domain service object is a sort of factory for a DomainContext, then you don't have much of a problem -- this becomes an exercise of how you configure Ninject to provide concrete objects and inject dependencies.
Here's general guidance on how you would structure your application -- bear in mind I don't have full understanding of your interfaces and classes:
public class GlobalApplication : NinjectHttpApplication {
protected override void RegisterRoutes(RouteCollection routes) {
// Your normal route registration goes here ...
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
// This function is resposible for creating a Ninject kernel. This is where
// the magic starts to happen.
protected override IKernel CreateKernel() {
var modules = new IModule[] {
new AutoWiringModule(),
new AutoControllerModule(
Assembly.GetExecutingAssembly()),
new ServiceModule()
};
return new StandardKernel(modules);
}
}
Note above that the easiest way to get Ninject to work is to derive your application class from the NinjectHttpApplication class. You will need to change your RegisterRoutes to an override method and will also be required to implement a method called CreateKernel. The CreateKernel method is responsible for returning the Ninject kernel which is itself the IoC container.
In the CreateKernel method, the Ninject-provided AutoControllerModule scans assemblies for MVC controller classes and registers them with the container. What this means is that dependencies on those controllers can now be injected by Ninject as it has become the controller provider for the application. The ServiceModule class is one that you need to create to register all of your services with Ninject. I'm guessing it would look something like this:
internal class ServiceModule : StandardModule {
public override void Load() {
Bind<IDomainService>()
.To<MyDomainService>()
.Using<OnePerRequestBehavior>();
Bind<DomainContext>()
.ToMethod( ctx => ctx.Kernel.Get<IDomainService>().CurrentDomainContext )
.Using<OnePerRequestBehavior>();
Bind<IService>()
.To<MyServiceType>()
.Using<OnePerRequestBehavior>();
}
}
Ninject's got a pretty expressive fluent interface for configuration. Note above that each statement basically associates a concrete class with an interface it implements. The "Using" phrase in the statement indicates to the Ninject kernel that the object will live for the life of the request only. So, for example, this means that anytime an IDomainService object is requested from the Ninject kernel during the same request, the same object will be returned.
As for you context objects, I'm taking a stab that your domain service creates these contexts and acts as a factory of sorts. In that regard, I bound instances DomainContext classes above to be produced by getting the value of the a property called CurrentDomainContext off the IDomainService. That's what the lambda above accomplishes. The nice thing about the "ToMethod" binding in Ninject is that you have access to a Ninject activation context object that allows you to resolve objects using the kernel. That's exactly what we do in order to get the current domain context.
The next steps are to ensure your objects accept dependencies properly. For example, you say that ITrainingService is used only in the TrainingController class. So, in that case I would ensure that TrainingController has a constructor that accepts an ITrainingService parameter. In that constructor, you can save the reference to the ITrainingService in a member variable. As in:
public class TrainingController : Controller {
private readonly ITrainingService trainingService;
public TrainingController(ITrainingService trainingService) {
this.trainingService = trainingService;
}
// ... rest of controller implementation ...
}
Remember that Ninject has already registered all of your controllers with the Ninject kernel, so when this controller is created and it's actions are invoked, you'll have a reference to the ITrainingService by way of the trainingService member variable.
Hope this helps you out. Using IoC containers can become quite confusing at times. Note, I highly recommend you check out the Ninject documentation -- it's a very well written introduction to Ninject as well as DI/IoC concepts. I've also left out discussion of the AutoWiringModule shown above; however, Nate Kohari (Ninject's creator) has a good write-up on his blog about this feature.
Good luck!
Im not exactly sure if I understand your problem completely, hopefully this bit of advice can help.
When using an IoC container you let the container handle object lifetime managment. I have only used Castle Windsor and StructureMap for dependency injection so I cant give you a concrete example for how to do this with Ninject.
Looking through the Ninject documentation I think you want to look at Activation Behaviours to specify object lifetime management.
Hope this helps.

Will IoC lead to too many params for ASP.NET MVC Controller constructor?

I have decided to use ASP.NET MVC for a website project and want to follow some of the best practices being written about.
So, I have separated out the Domain/Model into a separate project, created IRepositories and concrete repositories and have now turned my attention to Castle Windsor as the IoC.
The problem I now face is that for a particular Controller, on the constructor I will now have to pass in multiple IRepository parameters.
My questions are:
Have I perhaps created too many Repositories - in general, I map 1 repository to 1 entity class to 1 database table. Should my Repositories be containing effectively more than one entity/db table?
Have I missed the point with IoC's and Dependency Injection, and should I not be concerned with how params are passed into a Controller constructor?
To give some sort of context. Part of the website will show a google map of properties that is searchable by property type (Castle, House, Pub etc), location (postcode, city), opening time etc.
So, these searchable components are all separate entities PropertyType, Address.City, Address.Postcode.Lat+Long, OpeningTime.DateTime. Therefore, there are also 3 separate repositories that have to be passed into the SearchController constructor.
This is a simple example but I can envisage many more repository parameters being passed into other controllers in the future.
Hope all this makes sense.
Thanks for any answers or advice.
I wouldn't be concerned with how many parameters you're passing into your constructor the IoC will handle all the logic from that.
If your controller ends up with too many parameters, I would look at breaking up the functionality of your controllers, or move the logic into a service class maybe.
As for the Repositories, I usually go with a Generic Repository that would take a single Entity in its implementation. Then I have a service class that aggregates that information into logical units. In this scenario your controller only needs access to the service. For example:
interface IRepository<T>
{
IQueryable<T> GetAll();
T GetOne(int id);
void Save(T item);
void Delete(T item);
}
class OrderService
{
public OrderService(IReopository<Order> orderRepository, IRepository<OrderDetail> orderDetailRepository, IRepository<Payment> paymentRepository, etc) { }
public Order CreateOrder(List<OrderDetails> details)
{}
// .. other aggregate methods
}

Resources