大家好,又见面了,我是你们的朋友全栈君。
配置nhibernate的方式有两种,一种是通过xml文件的方式配置,还有就是通过class的方式配置。网上大多数是以xml的方式配置nhibernate,本文则已class的方式来配置,并通过IOC(依赖注入,本文以构造注入)的方式注册nhibernate。下面就以一个demo来说明配置、注入以及使用的方法。
创建一个工程,在工程下添加三个项目。
1、Web工程(demo采用的是MVC框架),在项目下添加一个IOC文件夹,并在文件夹下添加一下类,工程图如图所示:
2、web.Model
3、web.Service
IOC
a. NHibernateModule.cs —-用于nhibernate的注册
namespace Web.Ioc.Module
{
public class NHibernateModule :Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
/* one application have only one ISessionFactory */
builder.Register(c => new SessionFactoryProvider())
.As<ISessionFactoryProvider>()
.SingleInstance();
/* should be instance per http request to ensure one session per request model */
builder.Register(c => new SessionProvider(c.Resolve<ISessionFactoryProvider>()))
.As<ISessionProvider>()
.InstancePerRequest();
/* should be instance per http request to ensure one session per request model */
builder.Register(c => new UnitOfWork(c.Resolve<ISessionProvider>()))
.As<IUnitOfWork>()
/* must be, to commit transaction, to close session, or will lost data and occupied db connection */
//.OnRelease(uow => uow.Close()) // 如果有继承IDispose接口 则可以不用显示调用
.InstancePerRequest();
}
}
}
b. ServiceModule.cs —–用于service的注册
namespace Web.Ioc.Module
{
public class ServiceModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterGeneric(typeof(Service<>))
.As(typeof(IService<>))
.InstancePerRequest();
}
}
}
c. IocConfig.cs 用于注册nhibernate和service
namespace Web.Ioc
{
public class IocConfig
{
public static void Register(/*params Assembly[] contorllerAssemblies*/)
{
var builder = new ContainerBuilder();
builder.RegisterModule(new NHibernateModule());//注册nhibernate
builder.RegisterModule(new ServiceModule());//注册service
// register controller.
//注册Controller。因为框架是采用构造注入的方式
builder.RegisterControllers(typeof(MvcApplication).Assembly);
// register api controller
builder.RegisterApiControllers(typeof(MvcApplication).Assembly);
// register filters
// global filters is not working
builder.RegisterFilterProvider();
var container = builder.Build();
// Configure contollers with the dependency resolver
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// Configure Web API with the dependency resolver
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
}
}
在Global.asax的Application_Start调用Register。如图:
Web.Model:该项目先主要存放数据实体以及实体对应数据库的映射。即nhibernate的mapping。
demo中的实体类:
namespace Web.Model
{
public class Barcode : EntityBase
{
public Barcode()
{
Active = 0;
}
public virtual string ItemNumber { get; set; }
public virtual long LastSerialNbr { get; set; }
public virtual long MinSerialNbr { get; set; }
public virtual long MaxSerialNbr { get; set; }
public virtual int Active { get; set; }
public virtual int CreatedId { get; set; }
public virtual DateTime CreatedTime { get; set; }
public virtual int ModifiedId { get; set; }
public virtual DateTime ModifiedTime { get; set; }
}
}
demo中的mapping类:
namespace Web.Model.Mapping
{
public class BarcodeMapping : EntityBaseMapping<Barcode>
{
public BarcodeMapping()
: base("wp_barcode")
{
Property(b => b.ItemNumber, m => m.Column("item_number"));
Property(b => b.LastSerialNbr, m => m.Column("last_serial_nbr"));
Property(b => b.MinSerialNbr, m => m.Column("min_serial_nbr"));
Property(b => b.MaxSerialNbr, m => m.Column("max_serial_nbr"));
Property(b => b.Active, m => m.Column("active"));
Property(b => b.CreatedId, m => m.Column("created_id"));
Property(b => b.CreatedTime, m => m.Column("created_time"));
Property(b => b.ModifiedId, m => m.Column("modified_id"));
Property(b => b.ModifiedTime, m => m.Column("modified_time"));
}
}
}
Web.Service:—-该模块主要包含用与nhibernate的ISession注册的类,以及数据库的交互。主要类:
SessionProvider :获取nhibernate的session
namespace Web.Service
{
/// <summary>
/// wrapping ISesion so that other assembly needn't to reference NHibernate.dll
/// </summary>
public class SessionProvider : ISessionProvider
{
private readonly Lazy<ISession> session;
public ISession Session
{
get { return session.Value; }
}
public SessionProvider(ISessionFactoryProvider sessionFactoryProvider)
{
session = new Lazy<ISession>(() => sessionFactoryProvider.SessionFactory.OpenSession());
}
}
}
SessionFactoryProvider :注册数据库连接以及mapping
using System.Data;
using System.Reflection;
using System.Linq;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
using Web.Model.Mapping;
namespace Web.Service
{
/// <summary>
/// wrapping ISesionFactory so that other assembly needn't to reference NHibernate.dll
/// </summary>
public class SessionFactoryProvider : ISessionFactoryProvider
{
private static readonly ISessionFactory sessionFactory;
private static Configuration Configuration { get; set; }
#region ISessionFactoryProvider 成员
public ISessionFactory SessionFactory
{
get { return sessionFactory; }
}
#endregion
static SessionFactoryProvider()
{
Configuration = BuildConfiguration();
sessionFactory = Configuration.BuildSessionFactory();
}
//注册pgsql
private static Configuration BuildConfiguration()
{
var cfg = new Configuration();
cfg.DataBaseIntegration(db =>
{
db.ConnectionStringName = "pgsqlConn";//对应config中的数据库连接字符串
db.Dialect<PostgreSQL82Dialect>();
db.Driver<NpgsqlDriver>();
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
db.IsolationLevel = IsolationLevel.ReadCommitted;
db.BatchSize = 100;
db.LogFormattedSql = true;
db.AutoCommentSql = true;
#if DEBUG
db.LogSqlInConsole = true;
#endif
});
cfg.AddMapping(BuildMappings());
/* Not supported in PostgreSQL */
//SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
return cfg;
}
/// <summary>
/// 通过Mapping映射的方式注册Nhibernate
/// </summary>
/// <returns></returns>
private static HbmMapping BuildMappings()
{
var mapper = new ModelMapper();
mapper.AddMappings(Assembly
.GetAssembly(typeof(TestMapping))//获取TestMapping所在的程序集,即Web.Model
.GetExportedTypes()
.Where(t => t.Name.EndsWith("Mapping")));
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
return mapping;
}
//通过xml的方式注册nhibernate
// public static string BuildMappingsXml()
// {
// var mapper = new ModelMapper();
// mapper.AddMappings(Assembly
// .GetAssembly(typeof(UserMapping))
// .GetExportedTypes()
// .Where(t => t.Name.EndsWith("Mapping")));
// var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
// return mapping.AsString();
// }
}
}
最后调用的方式就特别简单了,在controller中(demo为homeController)
private readonly IService<Barcode> testService;//声明对象
//以构造函数的方式注入
public HomeController(IService<Barcode> testService)
{
this.testService = testService;
}
public ActionResult Index()
{
List<Barcode> list = testService.Queryable(o => o.Active == 0).ToList();//调用service
return View();
}
在web.config中添加连接字符串:
<connectionStrings> <add name="pgsqlConn" connectionString="Server=xxx.xxx.xx.xx;Port=****;User Id=****;Password=****;Database=****;" / </connectionStrings>
demo源代码:
源代码
ps:项目采用NuGet管理dll,为防止上传文件过大,所有未上传packages文件夹。下好代码后,直接重新生成,即可自动还原NuGet包。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/159185.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...