我一直将 Ninject 与我的 MVC 3 应用程序一起使用,但我正在尝试更改我的数据对象的模式以使用 UnitOfWork,但我无法弄清楚如何让 Ninject 正确处理这个问题。
我知道我的类实现在我的控制台应用程序中像这样手动构建时起作用:
IDatabaseFactory factory = new DatabaseFactory();
IUnitOfWork worker = new UnitOfWork(factory);
IBlogCategoryDao dao = new BlogCategoryDao(factory);
IBlogCategoryService service = new BlogCategoryService(dao);
BlogCategory category = service.GetById(id);
try
{
if (category != null)
{
service.Delete(category);
worker.Commit();
Console.WriteLine("Category deleted successfully!");
}
else
{
Console.WriteLine("Entity doesn't exist.");
}
}
catch (Exception ex)
{
Console.WriteLine("Error deleting category: {0}", ex.Message);
}
Run Code Online (Sandbox Code Playgroud)
在我的 MVC 3 应用程序中,我使用的是 Ninject.MVC3 NuGet 包,这是在 RegisterServices 方法中。
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>(); …Run Code Online (Sandbox Code Playgroud) 我想我的工作单元可能会在我的架构中设置错误.这是我目前拥有的(缩进显示顺序):
HttpRequest.Begin()
UnitOfWork.Begin()
Session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
Run Code Online (Sandbox Code Playgroud)
在这里,我使用NHibernate调用各种服务来执行crud.当我想对数据库进行更改(更新/保存)时,我调用此代码:
using (var transaction = unitOfWork.Session.BeginTransaction())
{
try
{
// These are just generics
ret = (Key)unitOfWork.Session.Save(entity);
transaction.Commit();
rb.unitOfWork.Session.Clear();
}
catch
{
transaction.Rollback();
rb.unitOfWork.Session.Clear();
rb.unitOfWork.DiscardSession();
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
当HttpRequest结束时,我执行以下步骤:
UnitOfWork.Commit()
Transaction.Commit() // This is my sessions transaction from the begin above
Run Code Online (Sandbox Code Playgroud)
我遇到了能够回滚大批量进程的问题.因为我在我的CRUD层中提交我的事务,如上所示,我的事务不再处于活动状态,当我尝试在UnitOfWork中回滚时,由于事务已经提交,它什么都不做.我在我的CRUD层中提交代码的原因是我可以尽可能快地保留我的数据,而不会长时间锁定数据库.
在上述情况下采取的最佳行动方案是什么?我是否只进行了不提交批处理作业的特殊CRUD操作,只是在我的工作结束时处理提交,或者我的逻辑是否与我的UnitOfWork和Session Per Request有关?有什么建议?
所以我想解决的问题是这个; 我们正在使用Entity Framework来访问具有1200-1500个表的Oracle数据库.现在请注意,我们并没有全部访问它们,但可能有800多个访问权限.我们正在使用UnitOfWork - > Repository - > Service模式并且效果很好,但是我们正试图弄清楚我们是否应该有一个大的DbContext,或者是特定于手头任务的多个小上下文.
我们的UnitOfWork使用EFUnitOfWorkBase进行设置,如下所示:
public abstract class EFUnitOfWorkBase : IUnitOfWork
{
private bool isDisposed = false;
public DbContextBase Context { get; set; }
protected EFUnitOfWorkBase(DbContextBase context)
{
Context = context;
}
public int Commit()
{
return Context.SaveChanges();
}
public void Dispose()
{
if (!isDisposed)
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
isDisposed = true;
if (disposing)
{
if (this.Context != null)
this.Context.Dispose();
}
}
public IRepository<TEntity> GetRepository<TEntity>() where TEntity : Common.EntityBase<TEntity>
{
return …Run Code Online (Sandbox Code Playgroud) 我在我的c#代码中调用了我的数据库,如下所示:
var filter = new PrioritizeSessionFilter()
.Add(DbTable.PrioritizeSession.Columns.IsArchived, Comp.Equals, false);
var list = UnitOfWork.PrioritizeSessions.Query(filter);
Run Code Online (Sandbox Code Playgroud)
有没有办法我一次只能退回10件物品而不是一次退回所有物品?我可以创建一个过滤器吗?
我有一些构造函数的问题,controller并且service被调用controller.
这是我的服务:
// model state dictionary for validation
private ModelStateDictionary _modelState;
// initialize UnitOfWork
private IUnitOfWork _unitOfWork;
public TownService(ModelStateDictionary modelState, IUnitOfWork unitOfWork)
{
_modelState = modelState;
_unitOfWork = unitOfWork;
}
Run Code Online (Sandbox Code Playgroud)
现在在我的控制器中我想创建新服务,传递控制器this.ModelState但不想添加UnitOfWork内部控制器.
像这样的东西:
private ITownService _townService;
public TownController()
{
_townService = new TownService(this.ModelState, null);
}
Run Code Online (Sandbox Code Playgroud)
所以考虑的一切UnitOfWork都是在服务内部完成的.控制器只是传递它自己modelState,服务是创建新的服务UnitOfWork.
这可能也是好方法吗?我怎样才能做到这一点?或者我应该new UnitOfWork在控制器中添加而不是null参数?
因为我想尽可能地分离Core,DAL,Web,以便一切都发挥作用,并且在控制器和服务中添加UnitOfWork似乎是不好的方式......
谢谢.
.net asp.net-mvc dependency-injection unit-of-work service-layer
我有一个Web API 2项目正在实现自定义IAuthenticationFilter,如下所示.
我的问题是Unity没有在BasicAuthenticator类中注入UnitOfWork.正如预期的那样,Unity成功地在控制器中注入了UnitOfWork.
public class BasicAuthenticator : Attribute, IAuthenticationFilter
{
[Dependency]
public UnitOfWork UoW { get; set; }
public bool AllowMultiple { get { return false; } }
public Task AuthenticateAsync(HttpAuthenticationContext context,
CancellationToken cancellationToken)
{
// ignore missing implementation
context.Principal = new ClaimsPrincipal(new[] { id });
return Task.FromResult(0);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
CancellationToken cancellationToken) {}
}
Run Code Online (Sandbox Code Playgroud) c# entity-framework unity-container unit-of-work asp.net-web-api2
实际上我正在使用Linq和UOW(工作单元),我正在使用linq轻松访问bbdd.我知道如果我想获得一个表的第一行,我可以这样做:
int test4 = (from p
in uow.ProductR.context.product
where p.Id == 1715 select p.Id).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
这将在SQL Server中执行:
SELECT TOP (1)
[Extent1].[Id] AS [Id]
FROM [dbo].[product] AS [Extent1]
WHERE 1715 = [Extent1].[Id]
Run Code Online (Sandbox Code Playgroud)
我的问题是,我可以使用LINQ对我的UOW的通用存储库进行反对吗?我的意思是,当我执行时
int test2 = uow.ProductR.Get(p => p.Id == 1715).Select(p => p.Id).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
要么
var test3 = uow.ProductR.Get(p => p.Id == 1715).Select(p => new { p.Id });
Run Code Online (Sandbox Code Playgroud)
在SQL Server中我得到:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
FROM [dbo].[product] AS [Extent1]
WHERE 1715 = [Extent1].[Id]
Run Code Online (Sandbox Code Playgroud)
当然,用第二种方式,当数据库有500k行时,它会很慢.(我有更多列,不仅仅是2)
编辑:这是带有GET声明的类
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where …Run Code Online (Sandbox Code Playgroud) 简短而简单的问题:
如何判断 Doctrine PHPEntity对象是新的?
新的-我的意思是不在数据库中并且它不是“更新”操作。最重要的是 - 我需要在没有任何查询的情况下检查它的方法,例如:
$manager->findOne($something);
Run Code Online (Sandbox Code Playgroud)
实际上有时我尝试检查“ID 是否为空”,但我不能 100% 确定这个方法是否有效。以及这个问题的其他提示或可能的核心 - 我看到了类似的东西:
$manager->getUnitOfWork()->isInIdentityMap($object);
Run Code Online (Sandbox Code Playgroud)
看起来不错,但我找不到实际的功能isInIdentityMap。如果它被保留或删除,这是真的吗?这个函数什么时候说 true 和 false?
//EDIT
我需要检测第一次创建的实体对象- 仅存在于 php 中,但不存在于数据库中。当然,从数据库加载实体以应用更新对我来说并不新鲜 - 例如:
当您创建Comment对象时,您需要递增commentCounter,但仅当您第一次刷新此注释时才应递增。您不想在更新或删除现有评论时增加它。如何检查评论是新的并且计数器应该增加。
请在答案中解释为什么你的方法好/更好
鉴于 EF Core 已经实现了存储库模式 ( DbSet) 和工作单元 ( DbContext),我可以DbSet像这样直接在我的存储库中使用吗?
public class MyEfRepository : IMyRepository
{
private readonly DbSet<MyModel> _myModels;
public MyEfRepository(MyDbContext ctx)
{
_myModels = ctx.MyModels;
}
public MyModel FindById(Guid id)
{
return _myModels.Where(x => x.Id == id).SingleOrDefault();
}
}
Run Code Online (Sandbox Code Playgroud)
并按以下方式实施工作单元?
public class MyEfUnitOfWork : IMyUnitOfWork
{
private readonly MyDbContext _ctx;
public IMyRepository MyModels { get; }
public MyEfUnitOfWork(MyDbContext ctx, MyEfRepository repo)
{
_ctx = ctx;
MyModels = repo;
}
void Commit() => _ctx.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
我想知道,因为我正在阅读的每一篇指南都建议将整个内容注入存储库以及通过它进行访问 …
c# unit-of-work repository-pattern dbcontext entity-framework-core
我在mvc5项目中使用UnitOfWork模式。
我有一个带有服务的BLL层。
public class StudentService
{
private readonly IUnitOfWork _db;
public StudentService(IUnitOfWork uow)
{
_db = uow;
}
public IEnumerable<StudentView> GetStudentViews()
{
List<Student> students = _db.Students.GetAll().ToList();
return Mapper.Map<List<Student>, List<StudentView>>(students);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试在mvc控制器中使用此服务时,出现错误:“没有为此对象定义无参数构造函数。”
public class StudentController : Controller
{
private readonly StudentService _service;
public StudentController(StudentService service)
{
_service = service;
}
// GET: Student
public ActionResult Index()
{
IEnumerable<StudentView> studentViews = _service.GetStudentViews();
return View("Index", studentViews);
}
}
Run Code Online (Sandbox Code Playgroud)
我没有无参数构造函数,但是如何在控制器中将我的服务与无参数构造函数一起使用?
我将DI用于UnitOf工作:
public class ServiceModule : NinjectModule
{
private string connection;
public ServiceModule(string connection) …Run Code Online (Sandbox Code Playgroud) unit-of-work ×10
c# ×6
asp.net-mvc ×3
linq ×2
.net ×1
asp.net ×1
dbcontext ×1
doctrine-orm ×1
nhibernate ×1
php ×1
sql-server ×1
symfony ×1