Profile ninject in mvc3 web application - asp.net-mvc-3

I am using Ninject together with MVC3 to inject my controller dependencies. Sometimes I get slow timings in MVC Mini profiler even before the controller actions are executed. Since I don't do much before that time I thought it might be an issue with my usage of Ninject. Is there an existing way to get some timing information from ninject? Perhaps a config option to log how long dependency resolution took or if not what would be a good way to add this myself, is there a class I can extend or wrap?

You can write a decorator for the NinjectDependencyResolver by implementing the IDependencyResolver interface and replace it on the DependencyResolver.
DependencyResolver.SetResolver(new ProfilingResolver(DependencyResolver.Current));
public class ProfilingResolver : IDependencyResolver
{
private readonly IDependencyResolver decoratedResolver;
public ProfilingResolver(IDependencyResolver decoratedResolver)
{
this.decoratedResolver = decoratedResolver;
}
public object GetService(Type serviceType)
{
using (MiniProfiler.Current.Step("Get_" + serviceType.Name))
{
return this.decoratedResolver.GetService(serviceType);
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
using (MiniProfiler.Current.Step("GetAll_" + serviceType.Name))
{
return this.decoratedResolver.GetServices(serviceType);
}
}
}

Firstly, my default answer would be:-
I've never seen DI showing up as a statistically significant percentage of anything interesting in a profile. Go Compose!
(This post started life as a comment:- #olle have you looked at the source? There are a number relatively simple extensions that 'wrap' the resolution process and shouldnt be too complex to grok. Given that you're using the Mini Profiler and it's pretty easy to stuff things into, it'd seem to be a relatively straightforward extension to do. I know this is a PITA response to get on a forum but I personally am thankful for being told to go Use The Source a few years back - the Ninject code base and its tests are a genuine joy to read.)

Related

Dependecy Injection in MVC 5 with ajax calls

So I recently found out about dependency injection and read a lot about the pros and cons and I was curious if it would be "good" using it in my app as i couldn't find an example of something like I have at the moment.
My app at the moment is 100% based on Ajax requests my typical controller looks like this:
public JsonResult Controller()
{
getStuff from the model
return JSON(info from controller)
}
Is DI a good choice for this situation? Or is are the benefits (if any) slim to none?
PS: I don't know if this matter much, but I only use 1 database.
If you have a large application with multiple dependencies then DI is a good choice. Even if your app is relatively small and only requires the database connection to be injected, this could be a good starting point for you into DI.
For the code example you provided, assuming you're using controller injection and you require a database connection, you'll end up with something similar to:
public class MyController
{
IDatabase database;
public MyController(IDatabase database)
{
this.database = database;
}
public JSONResult MyControllerMethod()
{
var myData = database.GetData();
return JSON(myData)
}
}
Then you would need to configure your DI container so it knows which concrete classes to inject for which interfaces - depending on the framework you use, this will differ slightly.
Given you don't have a lot of experience with it, keep in mind there will be a bit of a learning curve while you get your head around it. I'm assuming you're using WebAPI for your AJAX calls in which case this page is an excellent resource to get you started - http://www.asp.net/web-api/overview/advanced/dependency-injection

Is there any way to intercept all Linq to SQL queries?

I've built some code that can rebuild expression trees so I can avoid triggering the no supported translation to SQL exception and it works fine as long as I call my function to replace the iqueryable. The problem is that I'd like it to automatically be applied to all queries in my project without having to worry about calling this function on each one separately. Is there any way that I can intercept everything?
I've tried using Reflection.Emit to create a wrapping provider and using reflection to replace it on the data context and it turns out that even with Reflection.Emit I can't implement the internal IProvider interface.
I've also tried replacing the provider with a RealProxy based class and that works for non-compiled queries, but the CompiledQuery.Execute method is throwing an exception because it won't cast to the SqlProvider class. I tried replacing the response to the Compile method on the provider with another proxy so I could intercept the Execute call, but that failed a check on the return type being correct.
I'm open to any other ideas or ways of using what I've already tried?
It's hard to tell whether this is an applicable solution without seeing your code, but if you have a DI-friendly app architecture you can implement an interceptor and have your favorite IoC container emit the appropriate type for you, at run-time.
Esoteric? A little. Consider an interface like this:
public interface ISomeService
{
IEnumerable<SomeEntity> GetSomeEntities();
// ...
}
This interface might be implemented like this:
public class SomeService : ISomeService
{
private readonly DbContext _context // this is a dependency!
private readonly IQueryTweaker _tweaker; // this is a dependency!
public SomeService(DbContext context, IQueryTweaker tweaker) // this is constructor injection!
{
_context = context;
_tweaker = tweaker;
}
public IEnumerable<SomeEntity> GetSomeEntities()
{
return _tweaker.TweakTheQuery(_context.SomeEntities).ToList();
}
}
Every time you implement a method of the ISomeService interface, there's always a call to _tweaker.TweakTheQuery() that wraps the IQueryable, and that not only gets boring, it also feels like something is missing a feature - the same feeling you'd get by wrapping every one of these calls inside a try/catch block, or if you're familiar with MVVM in WPF, by raising this annoying PropertyChanged event for every single property setter in your ViewModel.
With DI Interception, you factor this requirement out of your "normal" code and into an "interceptor": you basically tell the IoC container that instead of binding ISomeService directly to the SomeService implementation, you're going to be decorating it with an interceptor, and emit another type, perhaps SomeInterceptedService (the name is irrelevant, the actual type only exists at run-time) which "injects" the desired behavior into the desired methods. Simple? Not exactly.
If you haven't designed your code with DI in mind (are your dependencies "injected" into your classes' constructor?), it could mean a major refactoring.
The first step breaks your code: remove the IQueryTweaker dependency and all the TweakTheQuery calls from all ISomeService implementations, to make them look like this - notice the virtualness of the method to be intercepted:
public class SomeService : ISomeService
{
private readonly DbContext _context
public SomeService(DbContext context)
{
_context = context;
}
public virtual IEnumerable<SomeEntity> GetSomeEntities()
{
return _context.SomeEntities.ToList();
}
}
The next step is to configure the IoC container so that it knows to inject the SomeService implementation whenever a type's constructor requires an ISomeService:
_kernel.Bind<ISomeService>().To<SomeService>();
At that point you're ready to configure the interception - if using Ninject this could help.
But before jumping into that rabbit's hole you should read this article which shows how decorator and interceptor are related.
The key point is, you're not intercepting anything that's internal to LINQ to SQL or the .NET framework itself - you're intercepting your own method calls, wrapping them with your own code, and with a little bit of help from any decent IoC container, you'll be intercepting the calls to methods that call upon Linq to SQL, rather than the direct calls to Linq to SQL itself. Essentially the IQueryTweaker dependency becomes a dependency of your interceptor class, and you'll only code its usage once.
An interesting thing about DI interception, is that interceptors can be combined, so you can have a ExecutionTimerServiceInterceptor on top of a AuditServiceInterceptor, on top of a CircuitBreakerServiceInterceptor... and the best part is that you can configure your IoC container so that you can completely forget it exists and, as you add more service classes to the application, all you need to do is follow a naming convention you've defined and voilà, you've just written a service that not only accomplishes all the strictly data-related tasks you've just coded, but also a service that will disable itself for 3 minutes if the database server is down, and will remain disabled until it's back up; that service also logs all inserts, updates and deletes, and stores its execution time in a database for performance analysis. The term automagical seems appropriate.
This technique - interception - can be used to address cross-cutting concerns; another way to address those is through AOP, although some articles (and Mark Seeman's excellent Dependency Injection in .NET) clearly demonstrate how AOP frameworks are a less ideal solution over DI interception.

Passing User Info to MVC Controller

I am looking at various methods to implement Authentication in my MVC3 app. I would like to use my own code to do the authentication – something similar to Is it possible to create a Logon System with ASP.NET MVC but not use the MembershipProvider? (I know that there are other methods.) I would like to know once I authenticate a user using one of these methods, how do I get the user information to the Controller constructor. (By user information I mean username or userID).
One of the options I considered is putting that info into the Session. This works, but it is difficult to test since I get the Session out of the Context which does not exist during the test.
I would appreciate any ideas for how to pass user info to the controller constructor.
No. Do not use Session for authentication. It's less secure, and unstable (sessions can be destroyed at will by the server).
In MVC, you don't need to use membership at all, but.. and I will make a point of emphasizing the but... Doing authentication correctly is not a trivial task. It's very very very easy to get it wrong and not even realize it. Even if you know what you're doing. It's something that should be heavily analyzed, tested, verified, and re-analyzed.
I would suggest, if you don't want to extend this effort, you should probably just use the default providers (there are several you can choose from).
But in any event, if you are determined to do it yourself, all you need is some way to verify the user. MVC does not integrate with the membership provider like WebForms does. It uses it for convenience. If you look in the default AccountController that is generated for you if you create an Internet project, all it does is call Membership.VerifyUser().
The truly important thing is the Authentication cookie system, which MS provides in the form of the FormsAuthentication class. I would VERY strongly recommend using this for the cookie management, unless you REALLY REALLY REALLY know what you are doing.
Just look in the AccountController, and it should be very obvious how this works. FormsAuthentication is the part that integrates into the app and tells asp.net that the user has already been authenticated. It uses a secure, encrypted cookie, and it's well designed (it even allows you to store your own additional data in an encrypted format).
Forms Authentication is a set of classes that work together to provide a transparent authentication mechanism, and is integrated into MVC and Asp.net WebForms. They are basically an implementation of the IPrincipal and IIdentity system, which is integral to asp.net (if you type User.IsAuthenticated this uses the IPrincipal interface).
In my original post I was looking at passing User Info to the Controller constructor. I did not want the Controller to depend on HttpContext, because this would make it difficult to test.
While I thank Mystere Man for his solution, I hope the following alternate solution would help someone. I have a small project (about a dozen controllers) so it is not too bad.
I basically created my custom ControllerFactory inheriting from DefaultControllerFactory:
public class MyCustomControllerFactory : DefaultControllerFactory
{
public MyCustomControllerFactory ()
{
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
return null;
}
else
{
//Example of User Info - Customer ID
string customerIDStr = requestContext.HttpContext.Session["CustomerID"].ToString();
int customerID = Int32.Parse(customerIDStr);
//Now we create each of the Controllers manually
if (controllerType == typeof(MyFirstController))
{
return new MyFirstController(customerID);
}
else if (controllerType == typeof(MySecondController))
{
return new MySecondController(customerID);
}
//Add/Create Controllers similarly
else //For all normal Controllers i.e. with no Arguments
{
return base.GetControllerInstance(requestContext, controllerType);
}
}
}
}
I then set the ControllerFactory in the Global.asax.cs Application_Start() method.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new MyCustomControllerFactory ());
}
P.S. I looked into using DI Containers like Ninject, but I think they were too complicated for my current project. I would look at them in a few months when it really makes sense to use them.

MVC3 using EF4.3 and Dependancy Injection issues

I have recently been learning MVC3 using Entity Framework 4.3 and Dependancy Injection so I can implement unit tests at a later date. I am now trying to implement some functions I have seen in various examples however I have hit a few issues that seem to stem from my use of dependancy injection and therefore I would like someone to point out where I am going wrong.
My first question is pretty simple; In most MVC3 examples I have seen, the access to the database is done in controllers, but when using dependancy injection I seem to need to refactor this code out to the implemented repository. Is this normal and correct?
My second more indepth issue is dealing with this simple example:
I have this method in my repository class which is pretty much copied from an online example (here). However I get an error regarding the Include part, and the intellisense does say that the variable needs to be a string. I have tried the original code from the link I mentioned earlier and that works fine, the only major difference between the project is that I am using dependancy injection.
public ExampleUser GetStruContractUser(int id)
{
ExampleUser user = context.ExampleUsers
.Include(i => i.ExampleRoles)
.Where(i => i.UserID == id)
.Single();
return user;
}
Changing the Include parameter to the following works fine.
public ExampleUser GetStruContractUser(int id)
{
ExampleUser user = context.ExampleUsers
.Include("ExampleRoles")
.Where(i => i.UserID == id)
.Single();
return user;
}
For reference this is my DbContext class that I am using:
public class EFDbContext : DbContext
{
public DbSet<ExampleUser> ExampleUsers { get; set; }
public DbSet<ExampleRole> ExampleRoles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<ExampleUser>().ToTable("User", "MySchema");
modelBuilder.Entity<ExampleRole>().ToTable("Role", "MySchema");
modelBuilder.Entity<ExampleUser>()
.HasMany(m => m.ExampleRoles)
.WithMany(t => t.ExampleUsers)
.Map(a =>
{
a.MapLeftKey("UserID"); // your PK column name in user table
a.MapRightKey("RoleID"); // your PK column name in role table
a.ToTable("UserRole", "MySchema"); // your join table name
});
}
}
Is this an issue due to my use of dependancy injection or is there something else going on that I am misunderstanding?
If you need more information, please ask and I will try and provide it.
Thanks very much.
Question 1:
Using DI doesn't force you to use a repository pattern, in fact they are not related. It's just a nice way to avoid tightly coupling your controller classes to the database context class, and being able to thus test those classes more easily. Repository gives you the ability to hide the implementation details of how you're accessing the DB, and allows you to switch ORM:s if that were to happen (and it never ever does). Repository relies on you to provide interfaces for your DbContext, and so does using DI.
What you want to do is use your DB through an interface nevertheless, and seeing as you're using DI, you could just inject the reference to the DbContext class in the constructor of your controllers, and let the DI controller do the work for you.
The reason it is preferable to pass in an interface that defines the repository to the Controller over passing an interface that defines your DbContext, is because making an interface of the latter can easily become overly complex, whereas sticking to a repository is much simpler. For simplicity though, I'd start with just using DbContext directly, and then expanding from there.
Question 2:
Include needs to contain the name of the table as a string. So your latter use of Include is correct, and the former isn't.
If I remember correctly, you can do this tho: ".Include(i => i.ExampleRoles.Name)" to achieve the same thing.
Yes, extracting your database layer (repositories / context) and then injecting it into your business layer (controllers) is very normal and a good way future proof your application. What if you ever wanted to change your database ORM from Entity Framework to something else? Having it tightly coupled with your controllers would create a huge headache.
Your second issue, with include, is unrelated to the dependancy injection.
Include on a dbset using lambdas an extension in System.Data.Entity. You'll need to include that reference if you want to use it.

Can IWindsorContainer be instantiated through a static method?

I'm still groping around a bit with Castle Windsor. At the moment all my pages which need an IWindsorContainer instantiate one themselves through a property:
private IWindsorContainer WindsorContainer
{
get
{
if (_windsorContainer == null)
{
_windsorContainer = new WindsorContainer(new XmlInterpreter(Server.MapPath("~/CastleWindsorConfiguration.xml")));
}
return _windsorContainer;
}
}
I'm getting a little tired of copying and pasting this property and the backing field from page to page! Also I don't really understand the life cycle of the IWindsorContainer.
I'd much rather get one of these through a static property of some class, but does anyone know if I can consider it threadsafe? How do you guys work with IWindsorContainer?
The standard and recommended practice is to have one instance of the container per application.
See these related questions for further information:
Usage of IoC Containers; specifically Windsor
How to get instance of service in Windsor Castle
And yes, Windsor is thread-safe.

Resources