我是 NHibernate 的新手,不太擅长 C#,但我正在学习。我有一个DataProvider
类,它使用 NHibernate 3 为我的应用程序提供数据。它的结构几乎与Steve Bohlen 的 NHibernate 之夏视频.
我注意到我将要大量重复我的代码,并且我想简化我的代码DataProvider
。例如,我有两个商务课程,名为Instrument
and Broker
。添加方法Instrument
in my DataProvider
is:
public int AddInstrument(Instrument instrument)
{
using (ITransaction tx = _session.BeginTransaction())
{
try
{
int newId = (int)_session.Save(instrument);
_session.Flush();
tx.Commit();
return newId;
}
catch (NHibernate.HibernateException)
{
tx.Rollback();
throw;
}
}
}
and the AddBroker
类看起来非常相似(只需查找并替换)。所以我想也许我可以使用泛型来解决这个问题。就像是:
public class DataProvider <TEntity>
{
public int AddEntity(TEntity entity)
{
using (ITransaction tx = _session.BeginTransaction())
{
try
{
int newId = (int)_session.Save(entity);
_session.Flush();
tx.Commit();
return newId;
}
catch (NHibernate.HibernateException)
{
tx.Rollback();
throw;
}
}
}
}
有了这个我可以传递一个Broker
, an Instrument
或者任何事情,我可以节省很多重复的代码。我遇到的问题是在我的Test
类我创建一个新的DataProvider
每次测试都像这样运行:
#region Fields
private DataProvider _provider;
private SessionManager _sessionManager;
private NHibernate.ISession _session;
#endregion
[SetUp]
public void Setup()
{
DatabaseSetUp();
_session = _sessionManager.GetSession();
_provider = new DataProvider(_session); // problem here
}
使用泛型我必须将对象类型传递给我的DataProvider
。你能想办法解决这个问题吗?我是一名新手程序员,我想知道我是否走在正确的道路上。我应该做一些完全不同的事情吗?
UPDATE
我尝试实施 Groo 的答案,但遇到了一些问题。这就是我所做的。
IRepo.cs
interface IRepo<T>
{
int Add<Entity>(Entity entity);
void Delete<Entity>(Entity entity);
void GetById<Entity>(int Id);
}
BaseRepo.cs
public abstract class BaseRepo <T> : IRepo <T>
{
private ISession _session;
#region SessionManagement
public BaseRepo(ISession session)
{
_session = session;
}
public ISession Session
{
set { _session = value; }
}
#endregion
public int Add<Entity>(Entity entity)
{
using (ITransaction tx = _session.BeginTransaction())
{
try
{
int newId = (int)_session.Save(entity);
_session.Flush();
tx.Commit();
return newId;
}
catch (NHibernate.HibernateException)
{
tx.Rollback();
throw;
}
}
}
// other methods omitted for brevity
}
IRepoFactory.cs
interface IRepoFactory
{
IInstrumentRepo CreateInstrumentRepo(ISession s);
}
RepoFactory.cs
public class RepoFactory : IRepoFactory
{
public IInstrumentRepo CreateInstrumentRepo(ISession s) // problem here
{
return new InstrumentRepo(s);
}
}
IInstrumentRepo.cs
interface IInstrumentRepo : IRepo<Instrument>
{
}
InstrumentRepo.cs
public class InstrumentRepo : BaseRepo<Instrument>, IInstrumentRepo
{
public InstrumentRepo(ISession s) : base(s) { }
}
在 RepoFactory.cs 中我收到此错误:
Inconsistent accessibility: return type 'MooDB.Data.IInstrumentRepo' is less accessible than method 'MooDB.Data.RepoFactory.CreateInstrumentRepo(NHibernate.ISession)'
我有什么想法吗?