Nhibernate (Fluent), Ninject.Mvc3, and Web Activator - asp.net-mvc

I am working on an ASP .NET Mvc 3 App and have installed Ninject.Mvc3 using Nuget. I now have the App_Start folder and then ninject class. I have seen plenty of examples on how to configure NHibernate in the Global.asax file. So how do I configure the session before handing it Ninject if I am using the Web Activator class? Do I just do it like normal in the global.asax?,

Bob Cravens has a nice series of posts on how to do this:
Using the Repository Pattern with MVC and NHibernate
http://blog.bobcravens.com/2010/06/the-repository-pattern-with-linq-to-fluent-nhibernate-and-mysql/
Using an IoC container (like Ninject) with a NHibernate inside ASP.NET MVC
http://blog.bobcravens.com/2010/07/using-nhibernate-in-asp-net-mvc/
Any responsible web developer knows that managing / disposing of objects and resources is critical to good web application development. Please make sure and read this bit too :-)
http://blog.bobcravens.com/2010/11/using-ninject-to-manage-critical-resources/

I don't know which example you are refering to. But for most of them you can do it the same way.

Now, in App_Start folder you have a file called NinjectMVC.cs, there is a method:
private static void RegisterServices(IKernel kernel)
{
}
You have to register all your services there, just the same way you did in global.ascx before.

Related

Are there any undesirable side-effects from bootstrapping from an assembly without any services embedded in it?

I just installed MVC5 and ServiceStack.Host.Mvc into a empty ASP.NET project. MVC for the Routing, Bundling/Minification and ServiceStack for everything else (IoC, Cache, ect.). This site will only be used to deliver views (SPA Islands I call them) and these rendered views will in turn call another ServiceStack RESTful API site.
So my questions is this "Since I have to bootstrap ServiceStack with the AppHostBase which wants an assembly with a Service in it, is there any harm if I just use the current assembly with-out any services as the snippet below illustrates?"
public AppHost()
: base("Website UI", typeof(MyRootNamespace.Global).Assembly) { }
Everything still seems to work in controllers that inherit from ServiceStackController, at least the IoC.
Thank you,
Stephen
Nope, ServiceStack just uses the list of assemblies specified in the AppHost constructor to scan and autowire any IService's it can find in those assemblies, which in this case there just wont be any.

Setting up Web API within WCF Project

I have a little bit of a "strange practise" question. The requirement on an architecture of our project is to setup Web API with (if possible) all MVC goodness within WCF project. That means that WCF and Web API web services would be stood up along each other within one project.
Is this even doable? I've given it a short go and found that even merging the web configs of two projects is very hard.
Thank you for your suggestions and comments,
Jakub
I followed these steps and it worked fine:
Make sure your WCF service is working correctly.
Install WebAPI to your project through Nuget Package Manager
Install-Package Microsoft.AspNet.WebApi
Create Controller folder and write your controller class and methods.
Create global.asax file
Register routes for your services in Application_Start method.
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
private void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpRoute(
"webapi_route",
"/{controller}/{action}/{id}",
new { controller = "controller_name", action = "method_name", id = RouteParameter.Optional }
);
RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(service_name)));
}
In fact there are no major restrictions on the use of the two technologies within the same project. By default wcf has a different "pipe line" than asp.net, but until this can be changed. Using the configuration below in web.config it is possible to configure wcf to use the same asp.net pipe line thus sharing the whole life cycle of the objects of the request. But do not believe that this approach is usual for all cases, other factors need to be considered to make that decision, for example, how do you plan to distribute your application? When you release a version of wcf you will also be releasing the web.api, in many cases you may not want this result.
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
It is possible but with losing the MVC goodness (that means that you will not be able to use for example the built in automatic online documentation for your web services).
Just install Web API through NuGet and then register your route in global.asax. Create your api controller and it should be all good.
EDIT 01.02.2017:
This is no longer true. Since Microsoft approach was to merge MVC and Web API controller. Now anything is possible.

What is your opinion on using MVCExtensions with Autofac

I would like to know your opinion on using MVCExtensions with Autofac..
I am using MVC Extensions with Autofac in my MVC 3 web app. I'm just not getting it why these extensions were created? I can't really say that it is makng my life easier. Everything that I did with Autofac in my global.asax.cs file I can do with the MVC extensions. I can register routes, controllers, my services and repositories, etc with just Autofac.
Any opinions why using these MVC extensions is maybe a better way to go?
I need to capture my errors in Application_Error. How do I get an instance of my registered logger? If I need to resolve dependencies some where else in my app how would I do this? This is how I register my logger:
builder.RegisterType<Logger>().As<ILogger>();
I can instantiate my logger but would rather like to use the registered logger.
Is there a tag for these extensions?
You should be able to access your logger through the DependencyResolver:
var logger = DependencyResolver.Current.GetService<ILogger>();

Ninject MVC together with WCF extension does not work with InRequestScope

I have gotten Ninject MVC to work with Ninject WCF to get it to work I added two lines to CreateKernel method
kernel.Bind<ServiceHost>().To<NinjectServiceHost>();
KernelContainer.Kernel = kernel;
The dependencies are injected, but the Dispose method is not called, I've tried both with InRequestScope and doing my own scope Func return OperationContext.Current as Scope object, but the dispose is not called.
Update 2012-09-05
This info is obsolete, for MVC and WCF download from Nuget Ninject.MV3 and Ninject.Extensions.WCF (3.x) the MVC Nuget template will add a Ninject bootstrapper NinjectWebCommon.cs and to add support in a svc for ninject eddit the svc xml (Right click / View markup) and add Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory" to the xml node
I can't reply to Remo's answer because I'm a stackoverflow n00b but the issue with the 'System.Runtime.CompilerServices.ExtensionAttribute' exception is that it has moved from System.Core in .net 4.0 to mscorlib in .net 4.5. If you install .net 4.5 the problem disappears. I think something was built with .net 4.5 in the mix. https://github.com/ninject/Ninject.Web.Common/issues/3 Sounds like it will be fixed soon.
As for the Wcf InRequestScope issue Remo gave me some help today on the google groups...
"add a new module that derives from "Ninject.GlobalKernelRegistrationModule" and load it into the kernel. This will be fixed for the final release though."
i.e. something like...
public class MyModule : Ninject.GlobalKernelRegistrationModule<WcfRequestScopeCleanup>
{
}
//And where you load your modules...
kernel.Load<MyModule>();
I recommend using Ninject 3.0.0-rc2 available from Nuget. InRequestScope works for both Web and WCF requests side a side.

How to properly decouple Structure Map dependency resolver from ASP.NET MVC web project?

While developing web project using ASP.NET MVC, I came up against a coupling problem.
When I build custom controller factory (or dependency resolver if using MVC 3), I need this factory to know somehow where to get dependencies from. Here's my code:
//from Global.asax.cs
DependencyResolver.SetResolver(new StructureMapControllerFactory());
class StructureMapControllerFactory: IDependencyResolver {
Container repositories;
public StructureMapControllerFactory()
{
repositories = new RepositoriesContainer();
}
//... rest of the implementation
}
class RepositoriesContainer: Container
{
public RepositoriesContainer()
{
For<IAccountRepository>().Use<SqlAccountRepository>();
//...
}
}
StructureMapControllerFactory class is responsible for injecting dependencies into a controller. As I said, it needs to know where to find these dependencies (I mean concrete classes, like services and repositories implementations).
I have a separate class library called MySite.Data, where all the implementation details live. Contracts, like IAccountRepository, live in library MySite.Contracts. Now, if I reference this MySite.Data library directly from MVC project, there will be a dependency between my site and implementation of its data retrieval. The question is how can I remove it? What are best practices in this situation?
I'm sure it does have a bunch of workarounds, just I haven't found any yet.
Well, as I see it, you can't do exactly that. Your MVC project really really needs to know about concrete classes it is going to use.
You will anyway have to provide those container registrations somewhere and you'll get the dependency on the project/assembly where that type is defined. Shortly, you have to reference MySite.Data from MVC project. Like that:
MySite.Data knows nothing about MVC project
MVC project knows the concrete repositories types to provide correct container registrations.
You can make life simpler with StructureMap Registry objects but you need to include those Registries somewhere as well. Typically those are in the main project or some "StructureMap-adapter" project but you'd need to make reference anyway.
I'd advise that you:
Use MVC3 and drop your custom IControllerFactory if you only use it for DI into your Controllers.
Use StructureMap Registry objects to provide each and every IoC registration ever needed.
Use StructureMap Assembly scanning capabilities to provide components discovery.
Use something much more common as a DependencyResolver, i.e. not a StructureMapControllerFactory but a CommonServiceLocator with StructureMap adapter instead.
Try to abstract from StructureMap itself inside your main app.
And, of course, don't be afraid of making references inside the main project - they have nothing about coupling. It doesn't decrease maintainability. But the wrong architecture does, so be worried about that, not simple reference.

Resources