我在用
目前我正在使用nhibernate,ninject与存储库模式和服务层.
所以我有这个
public class NhibernateSessionFactory
{
public ISessionFactory GetSessionFactory()
{
ISessionFactory fluentConfiguration = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("ConnectionString")))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Framework.Data.Mapping.TableAMap>().Conventions.Add(ForeignKey.EndsWith("Id")))
.ExposeConfiguration(cfg => cfg.SetProperty("adonet.batch_size", "20"))
.ExposeConfiguration(c => c.SetProperty("generate_statistics", "true"))
//.ExposeConfiguration(BuidSchema)
.BuildSessionFactory();
return fluentConfiguration;
}
private static void BuidSchema(NHibernate.Cfg.Configuration config)
{
new NHibernate.Tool.hbm2ddl.SchemaExport(config).Create(false, true);
}
public class NhibernateSessionFactoryProvider : Provider<ISessionFactory>
{
protected override ISessionFactory CreateInstance(IContext context)
{
var sessionFactory = new NhibernateSessionFactory();
return sessionFactory.GetSessionFactory();
}
}
public class NhibernateModule : NinjectModule
{
public override …Run Code Online (Sandbox Code Playgroud) 在我的ASP.NET MVC应用程序中,我使用工作单元和存储库模式进行数据访问.
使用工作单元类和在其中定义的存储库,我在控制器中获取相关的实体集.凭借我的初学者知识,我可以想到两种方法来获取业务模型并将其转换为视图模型.
目前我正在使用第一种方法,但我的控制器代码开始看起来很丑,很长时间用于具有大量属性的视图模型.
另一方面,我在想,因为我的存储库名为UserRepository(例如),它应该直接返回业务模型,而不是仅对单个视图有用的模型.
您认为哪一项更适合大型项目?还有另一种方法吗?
谢谢.
c# asp.net-mvc entity-framework unit-of-work repository-pattern
我使用EF Core 1.0(以前称为广告EF7)和ASP.NET Core 1.0(以前称为ASP.NET 5)作为RESTful API.
我希望将一些工作单元限定为一个http请求,以便在响应HTTP请求时,对DbContext所做的所有更改都将保存到数据库中,否则将不会保存(如果有的话)一些例外,例如).
在过去,我通过使用一个Action过滤器将NHAPnate用于此目的的WebAPI2,我在操作执行时开始事务,并在执行的操作上结束事务并关闭会话.这是http://isbn.directory/book/9781484201107推荐的方式
但是现在我使用Asp.Net Core(与Asp.Net Core Mvc虽然这不应该相关)和实体框架,据我所知,已经实现了一个工作单元.
我认为将中间件插入ASP.NET管道(在MVC之前)将是正确的做事方式.所以请求会:
PIPELINE ASP.NET:MyUnitOfWorkMiddleware ==> MVC Controller ==> Repository ==> MVC Controller ==> MyUnitOfWorkMiddleware
如果没有发生异常,我正在考虑让这个中间件保存DbContext更改,这样在我的存储库实现中我甚至不需要做dbcontext.SaveChanges(),所有内容都像集中式事务.在伪代码中我猜它会是这样的:
class MyUnitOfWorkMiddleware
{
//..
1-get an instance of DbContext for this request.
try {
2-await the next item in the pipeline.
3-dbContext.SaveChanges();
}
catch (Exception e) {
2.1-rollback changes (simply by ignoring context)
2.2-return an http error response
}
}
Run Code Online (Sandbox Code Playgroud)
这有意义吗?有没有人有类似的例子?我无法找到任何良好的做法或建议.
此外,如果我在MVC控制器级别使用此方法,则在POST新资源时无法访问数据库创建的任何资源ID,因为在保存dbContext更改之前不会生成ID(稍后在管道中)在我的中间件控制器完成执行后).如果我需要在控制器中访问新创建的资源ID,该怎么办?
任何建议将不胜感激!
更新1:我发现使用中间件实现此目的的方法存在问题,因为中间件中的DbContext实例与MVC(和存储库)生命周期中的实例不同.请参阅问题实体框架核心1.0 DbContext未限定为http请求
更新2 …
middleware unit-of-work entity-framework-core asp.net-core-1.0
(为文字墙道歉... :))
在我的Winfor应用程序中使用依赖注入正在创建大量的存储库上下文.我不确定我使用它的方式是对还是错,或者通常的做法是什么.
在过去的6个月里,我一直在制作ASP.NET MVC应用程序,它们使用Repository Pattern来实现Unit O fWork模式.最重要的是,我一直在所有这些Web应用程序上使用依赖注入,但取得了一些成功.
所以这是我连接我的存储库的一个例子.
public EntityFrameworkRepositoryRegistry()
{
For<IUnitOfWork>()
.HybridHttpOrThreadLocalScoped() // Lifecycle of the object.
.Use<SqlServerContext>() // My EF Context.
.Ctor<string>("connectionString").Is("name=SqlServer_EF")
.Ctor<string>("defaultContainerName").Is("Entities");
// Ayende's EFProf application :)
EntityFrameworkProfiler.Initialize();
Scan(x =>
{
x.TheCallingAssembly();
x.ExcludeNamespaceContainingType<Fake.FakeContext>();
x.WithDefaultConventions();
}
);
}
Run Code Online (Sandbox Code Playgroud)
好的 - 效果很好.这里要注意的主要是
KEWL.
现在,对于我的WinForm应用程序,我最初创建了一个Unit Of Work对象(还没有依赖注入)并且不断地将该婴儿传递给所有服务(然后到存储库).
对于这个win应用程序,它会命中数据库找出它需要解析的所有文本文件.(例如,25个文件).然后,对于每个文件,它创建一个新的Parser,读取每一行并将解析的数据放入db表中.精细.
问题是,这个概念正在被所有的Parsers共享,这严重地在整个商店中引发了错误.
那么我添加了一些依赖注入并使用上面的注册表代码.排序相同 - 很多严重的错误.这是因为再次为单线程创建了一个上下文 - > winform.
所以,我现在调整了Context的注册表以下内容: -
public EntityFrameworkRepositoryRegistry(bool isForTheWeb)
{
if (isForTheWeb)
{
For<IUnitOfWork>()
.HybridHttpOrThreadLocalScoped()
.Use<SqlServerContext>()
.Ctor<string>("connectionString").Is("name=SqlServer_EF")
.Ctor<string>("defaultContainerName").Is("Entities");
}
else
{
For<IUnitOfWork>()
.Use<SqlServerContext>()
.Ctor<string>("connectionString").Is("name=SqlServer_EF") …Run Code Online (Sandbox Code Playgroud) .net dependency-injection unit-of-work repository-pattern winforms
我有以下实现,并希望得到一些反馈,以确定它是否正确使用NHibernate进行会话和事务.
public interface IUnitOfWork : IDisposable
{
ISession CurrentSession { get; }
void Commit();
void Rollback();
}
public class UnitOfWork : IUnitOfWork
{
private readonly ISessionFactory _sessionFactory;
private readonly ITransaction _transaction;
public UnitOfWork(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
CurrentSession = _sessionFactory.OpenSession();
_transaction = CurrentSession.BeginTransaction();
}
public ISession CurrentSession { get; private set; }
public void Dispose()
{
CurrentSession.Close();
CurrentSession = null;
}
public void Commit()
{
_transaction.Commit();
}
public void Rollback()
{
if (_transaction.IsActive) _transaction.Rollback();
}
}
Run Code Online (Sandbox Code Playgroud)
Ninject绑定
Bind<IUnitOfWork>().To<UnitOfWork>().InTransientScope();
Bind<ISessionFactory>().ToProvider<NHibernateSessionFactoryProvider>().InSingletonScope(); …Run Code Online (Sandbox Code Playgroud) 我正在开发一个工作单元实现,它在Entity Framework 4.1和NHibernate中都有效.在下面找到我的实现细节的框架
IUnitOfWork定义
public interface IUnitOfWork
{
IRepository<LogInfo> LogInfos { get; }
IRepository<AppInfo> AppInfos { get; }
void Commit();
void Rollback();
}
Run Code Online (Sandbox Code Playgroud)
IRepository定义
public interface IRepository<T> where T : class, IEntity
{
IQueryable<T> FindAll();
IQueryable<T> FindWhere(Expression<Func<T, bool>> predicate);
T FindById(int id);
void Add(T newEntity);
void Remove(T entity);
}
Run Code Online (Sandbox Code Playgroud)
在NHibernate中实现UoW
public class NHibernateUnitOfWork : IUnitOfWork, IDisposable
{
public ISession Session { get; private set; }
public NHibernateUnitOfWork(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
Session = _sessionFactory.OpenSession();
_transaction = Session.BeginTransaction();
}
public …Run Code Online (Sandbox Code Playgroud) 我正在考虑使用EF 4开始一个新项目并浏览一些文章,我发现了一些关于EF的文章和存储库模式以及工作单元
(http://tdryan.blogspot.com/2011/03/another-entity-framework-4-repository_15.html和http://blogs.msdn.com/b/adonet/archive/2009/06/16/using -repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx)
我正在使用第一个(第1部分,第2部分和第3部分).它们非常相似.
在这种情况下,我是新手.我在这两个帖子之间感到困惑.我已经创建了所有内容,但我不知道如何开始使用上下文并添加一些实体.我发布了第二个链接,因为发布了实现它的方法.该ObjectContext来源于IUnitOfWork,所以我很困惑,以选择这两个的是更好地使用.
使用此示例和此实现提供的组合,我尝试创建一个解决方案,将UnitOfWork类与各个存储库分离,因为它们违反了开放 - 封闭原则,因为每次添加新存储库时都必须修改UnitOfWork类.我使用Unity作为IoC容器来连接依赖项.
我的问题是,在自动布线构成UnitOfWork,IDbContext和储存库(IEmployeeRepository和ICustomerRepository使用Unity)时,存储库将与的单独实例注入UnitOfWork,其中,当然,失败的目的.我需要在存储库之间共享上下文,似乎我错过了这个难题的一个部分 - 目前(参见服务层),UnitOfWork实例化将与UnitOfWork每个存储库的不同.
如何使用Unity和依赖注入将注入IUnitOfWork到服务层并将此实例化的共享 UnitOfWork类传递到相应的存储库?
这是我提出的(伪造的)解决方案:
库
public interface IRepository<TEntity> where TEntity : class
{
TEntity Create();
// omitted for brevity
}
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : class
{
private readonly DbContext _context;
public Repository(IUnitOfWork uow)
{
_context = uow.Context;
}
public virtual TEntity Create(TEntity entity)
{
return …Run Code Online (Sandbox Code Playgroud) entity-framework inversion-of-control unity-container unit-of-work repository-pattern
我目前正在开发MVC 3中的项目.我已将我的问题分开,因此有一些项目,如Core,Repository,UI,Services等.我实现了Repository,UnitOfWork,最重要的是State模式.
我正在使用Entity Framework 4.3来保存我的数据,并且我遇到了一个涉及当前状态持久性的相当烦人的情况.以下是一些类示例:
public class Request
{
public int RequestId { get; set; }
public State CurrentState { get; set; }
}
public abstract class State
{
[Key]
public string Name {get; set;}
public virtual void OpenRequest(Request request)
{}
public virtual void CloseRequest(Request request)
{}
}
public class RequestIsOpenState : State
{
public RequestIsOpenState()
{
this.Name = "Open";
}
public override void CloseRequest(Request request)
{
request.CurrentState = new RequstIsClosedState();
}
}
public class RequestIsClosedState : State
{
public …Run Code Online (Sandbox Code Playgroud) 我用实体框架6开发Web应用程序,并且在设计应用程序结构时遇到了困难.我的主要问题是如何在我的特定情况下处理依赖注入.
下面的代码是我希望应用程序的样子.我正在使用Autofac,但我想这对每个DI用户来说都足够了解:
public interface IUnitOfWork
{
bool Commit();
}
public class UnitOfWork : IUnitOfWork, IDisposable
{
private DbContext _context;
public UnitOfWork(DbContext context)
{
_context = context;
}
public bool Commit()
{
// ..
}
public bool Dispose()
{
_context.Dispose();
}
}
public class ProductsController : ApiController
{
public ProductsController(IProductsManager managet)
}
public class ProductsManager : IProductsManager
{
private Func<Owned<IUnitOfWork>> _uowFactory;
private IProductsDataService _dataService;
public Manager(Func<Owned<IUnitOfWork>> uowFactory, IProductsDataService dataService)
{
_dataService = dataService;
_uowFactory = uowFactory;
}
public bool AddProduct(ProductEntity product) …Run Code Online (Sandbox Code Playgroud) c# entity-framework dependency-injection unit-of-work autofac
unit-of-work ×10
c# ×4
nhibernate ×3
.net ×2
asp.net-mvc ×1
autofac ×1
linq ×1
middleware ×1
ninject ×1
ninject-2 ×1
repository ×1
session ×1
state ×1
transactions ×1
winforms ×1