I think you are missing some stuff regarding your DependencyScope. I use
Windsor, but here's my setup.
Global.asax
public class MvcApplication : System.Web.HttpApplication
{
public static String sessionkey = "current.session";
public static String transactionkey = "current.transaction";
public static IWindsorContainer Container;
public static ISessionFactory SessionFactory { get; set; }
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
Version version =
Assembly.GetExecutingAssembly().GetName().Version;
Application["Version"] = String.Format("{0}.{1}",
version.Major, version.Minor);
//make ASP.NET use castle container to create controllers
//this way we can inject NHibernate session into controllers
//create empty container
//scan this prject for Installers and install all the types in
the container
Container = new WindsorContainer().Install(FromAssembly.This());
//webapi controllers are different. they use the
DependencyResolver, not a ControllerFactory
GlobalConfiguration.Configuration.DependencyResolver = new
WindsorDependencyResolver(Container.Kernel);
//tell ASP.NET to get its controllers from Castle
ControllerBuilder.Current.SetControllerFactory(new
WindsorControllerFactory(Container.Kernel));
//initialize NHibernate
var nh = new NHInit();
nh.Initialize();
nh.InitializeAudit();
SessionFactory = nh.SessionFactory;
//tell container to return SessionFactory.GetCurrentSession()
every time ISession is requested
Container
.Register(Component.For<ISession>().UsingFactoryMethod(()
=> MvcApplication.CurrentSession)
.LifeStyle
.PerWebRequest);
}
protected void Application_OnEnd()
{
//dispose Castle container and all the stuff it contains
Container.Dispose();
}
public static ISession CurrentSession
{
get { return (ISession)HttpContext.Current.Items[sessionkey]; }
set { HttpContext.Current.Items[sessionkey] = value; }
}
protected void Application_BeginRequest()
{
CurrentSession = SessionFactory.OpenSession();
}
protected void Application_EndRequest()
{
if (CurrentSession != null)
CurrentSession.Dispose();
}
}
WindsorDependencyResolver.cs
public class WindsorDependencyResolver :
System.Web.Http.Dependencies.IDependencyResolver
{
private readonly IKernel _kernel;
public WindsorDependencyResolver(IKernel kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new WindsorDependencyScope(_kernel);
}
public Object GetService(Type serviceType)
{
return _kernel.HasComponent(serviceType)
? _kernel.Resolve(serviceType)
: null;
}
public IEnumerable<Object> GetServices(Type serviceType)
{
return _kernel.ResolveAll(serviceType).Cast<Object>();
}
public void Dispose()
{
_kernel.Dispose();
}
}
WindsorDependencyScope.cs
public class WindsorDependencyScope : IDependencyScope
{
private readonly IKernel _kernel;
private readonly IDisposable _scope;
public WindsorDependencyScope(IKernel kernel)
{
_kernel = kernel;
_scope = kernel.BeginScope();
}
public object GetService(Type serviceType)
{
return _kernel.HasComponent(serviceType) ?
_kernel.Resolve(serviceType) : null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _kernel.ResolveAll(serviceType).Cast<object>();
}
public void Dispose()
{
_scope.Dispose();
}
}
ApiControllersInstaller.cs
public class ApiControllersInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container,
IConfigurationStore store)
{
container.Register(Classes.FromThisAssembly()
.BasedOn<ApiController>()
.LifestylePerWebRequest());
}
}
On Sun, Oct 13, 2013 at 8:52 PM, vishwanath kenchanagoudar <
[email protected]> wrote:
> Hello All
>
> I am new to WebApi and Nhibernate both . We are using Nhibernate in our
> web application and I have learnt it from using it there . We use MVC3 .
> The Nhibernate Session is opened using the the global.asax . Below is the
> file
>
> using System;
> using System.Collections.Generic;
> using System.Linq;
> using System.Reflection;
> using System.Web;
> using System.Web.Http;
> using System.Web.Http.WebHost;
> using System.Web.Mvc;
> using System.Web.Optimization;
> using System.Web.Routing;
> using System.Web.SessionState;
> using Vish.Common.Utils.DateExtensions;
> using Vish.Common.RestApi.Config;
> using Vish.Common.RestApi.Controllers;
> using Vish.Common.RestApi.Filters;
> using Vish.Resi.RestApi.Config;
> using Vish.Resi.RestApi.Dependency;
> using Autofac;
> using Autofac.Integration.Mvc;
> using Microsoft.Web.Mvc;
>
> namespace Vish.Resi.RestApi
> {
> // Note: For instructions on enabling IIS6 or IIS7 classic mode,
> // visit http://go.microsoft.com/?LinkId=9394801
>
> public class WebApiApplication : System.Web.HttpApplication
> {
>
> private static void RegisterGlobalFilters(GlobalFilterCollection filters)
> {
> filters.Add(new LogHandleErrorAttribute());
> }
>
> void ConfigureApi(HttpConfiguration config)
> {
> config.DependencyResolver = new ApiDependencyResolver();
> }
>
> protected void Application_Start()
> {
>
> AreaRegistration.RegisterAllAreas();
> WebApiConfig.Register(GlobalConfiguration.Configuration);
> FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
> RouteConfig.RegisterRoutes(RouteTable.Routes);
> BundleConfig.RegisterBundles(BundleTable.Bundles);
>
> //Fixed Model binding bug with nullable parameters.
> ModelMetadataProviders.Current = new
> DataAnnotationsModelMetadataProvider();
>
> log4net.Config.XmlConfigurator.Configure();
>
> var builder = new ContainerBuilder();
>
> // TODO: Clean all this Autofac stuff up and refactor into separate config
> class/method
> builder.RegisterControllers(Assembly.GetExecutingAssembly(),
> typeof(ElmahController).Assembly)
> .OnActivated(e => ((Controller)e.Instance).TempDataProvider =
> e.Context.Resolve<ITempDataProvider>());
> builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
> builder.RegisterModelBinderProvider();
> builder.RegisterModule(new AutofacWebTypesModule());
>
> builder.RegisterType<ResiApiCookieTempDataProvider>().As<ITempDataProvider>();
>
> //builder.RegisterModule(new MembershipModule());
> //builder.RegisterModule(new ValidatorModule());
> builder.RegisterModule(new ServicesModule());
> builder.RegisterModule(new WebNHibernateModule());
> //builder.RegisterModule(new WebQuartzModule());
>
> var container = builder.Build();
>
> DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
>
> // Install the certificate
>
> //DependencyResolver.Current.GetService<ICrmService>().InstallCertificate();
>
> AreaRegistration.RegisterAllAreas();
>
> RegisterGlobalFilters(GlobalFilters.Filters);
> //RegisterRoutes(RouteTable.Routes);
>
> var settings = new WebAppSettings();
> //TimeProvider.CurrentTimeZone =
> TimeZoneInfo.FindSystemTimeZoneById(settings.ApplicationTimeZone);
> ConfigureApi(GlobalConfiguration.Configuration);
> }}}
>
> I have used a dependency resolver as i need to create a parametered
> contructor for the controller .
>
> using System;
> using System.Collections.Generic;
> using System.Linq;
> using System.Web;
> using System.Web.Http.Dependencies;
> using Vish.Resi.Data.Services;
> using Vish.Resi.Data.Services.Impl;
> using Vish.Resi.RestApi.Controllers;
> using NHibernate;
>
> namespace Vish.Resi.RestApi.Dependency
> {
> public class ApiDependencyResolver : IDependencyResolver
> {
> private readonly ISession _session;
> private static ISettings _settings;
> private static IDiscountService _discountService;
> private static IAuctionService _auctionService;
> private static IAuditService _auditService;
>
> public IDependencyScope BeginScope()
> {
> // This example does not support child scopes, so we simply return 'this'.
> return this;
> }
>
> public object GetService(Type serviceType)
> {
> if (serviceType == typeof(RestApiController))
> {
> return new RestApiController(_session);
> }
> else
> {
> return null;
> }
> }
>
> public IEnumerable<object> GetServices(Type serviceType)
> {
> return new List<object>();
> }
>
> public void Dispose()
> {
> // When BeginScope returns 'this', the Dispose method must be a no-op.
> }
>
> }
> }
>
> But when i reach the controller i see the session is empty as below
>
> using System;
> using System.Collections.Generic;
> using System.Linq;
> using System.Web;
> using System.Web.Http;
> using System.Web.Mvc;
> using System.Xml;
> using Vish.Resi.Data.Services;
> using Vish.Resi.Data.Services.Impl;
> using NHibernate;
>
> namespace Vish.Resi.RestApi.Controllers
> {
> public class RestApiController : ApiController
> {
> private static ISettings _settings;
> private static IDiscountService _discountService;
> private static IAuctionService _auctionService;
> private static IAuditService _auditService;
>
>
> private readonly ISession _session;
> //
> // GET: /RestApi/
>
> public RestApiController(ISession session)
> {
> _session = session;
> }
>
> public XmlDocument Get()
> {
> var productAdminService = new NhProductAdminService(_session, _settings,
> _discountService,
> _auctionService,
> _auditService);
> return productAdminService.GetXmlContract(new
> Guid("33cb5122-e3e1-4508-8e1d-a2430062e755"));
> }}}
>
> Please Advise . I have been in this state for a while now .
>
> --
> You received this message because you are subscribed to the Google Groups
> "nhusers" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To post to this group, send email to [email protected].
> Visit this group at http://groups.google.com/group/nhusers.
> For more options, visit https://groups.google.com/groups/opt_out.
>
--
You received this message because you are subscribed to the Google Groups
"nhusers" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/nhusers.
For more options, visit https://groups.google.com/groups/opt_out.