我一直在阅读很多文章,解释如何设置实体框架,DbContext以便每个HTTP Web请求只使用各种DI框架创建和使用一个.
为什么这首先是一个好主意?使用这种方法有什么好处?在某些情况下这是个好主意吗?在使用DbContext存储库方法调用实例化s 时,您是否可以使用此技术执行某些操作?
当我打电话说需要一种方法dbcontext为update或insert
,但只想要一个saveChange()像以下
行动:登录
TempDBEntity context = new TempDBEntity();
var temp = context.Users.Where(m => m.user_unique_id == 1).FirstOrDefault();
temp.timestamp = new DateTime();
temp.AddLog("Login");
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
功能:AddLog
public void AddLog(string activity){
TempDBEntity context2 = new TempDBEntity();
var log = new UserLog();
log.user_id = this.user_id;
log.activity = activity;
context2.UserLog.Add(log);
context2.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
如你所见,有两倍SaveChanges(),我只需要1 SaveChanges().
我应该DBContext作为另一个参数传递,AddLog()
还是应该dbcontext在这种情况下声明静态变量?
非常感谢.
背景:我使用SimpleInjector作为IoC的WCF服务,它为每个WCF请求创建DbContext实例.
后端本身就是CQRS.CommandHandlers有很多装饰器(验证,授权,日志记录,不同处理程序组的一些通用规则等),其中一个是Transaction Decorator:
public class TransactionCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
where TCommand : ICommand
{
private readonly ICommandHandler<TCommand> _handler;
private readonly IMyDbContext _context;
private readonly IPrincipal _principal;
public TransactionCommandHandlerDecorator(ICommandHandler<TCommand> handler,
IMyDbContext context, IPrincipal principal)
{
_handler = handler;
_context = context;
_principal = principal;
}
void ICommandHandler<TCommand>.Handle(TCommand command)
{
using (var transaction = _context.Database.BeginTransaction())
{
try
{
var user = _context.User.Single(x => x.LoginName == _principal.Identity.Name);
_handler.Handle(command);
_context.SaveChangesWithinExplicitTransaction(user);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当任何命令尝试链接在同一WCF请求中执行另一个命令时,会出现问题.我在这一行得到了一个预期的例外:
using (var …Run Code Online (Sandbox Code Playgroud) 我的 Windows 窗体应用程序中有一个文本框和一个按钮。当使用文本框中写入的值按下开始键时,应使用该值打开一个新表单。我想为每个打开的表单创建一个范围。当我关闭表单时,我想关闭相关范围。
如何使用简单的注入器创建自定义范围?
这是一个简单的示例代码
static class Program
{
static readonly Container container;
static Program()
{
container = new Container();
container.Register<MyProgram>();
//??
container.Register<MyCustomClass>(Lifestyle.Scoped);
container.Verify();
}
static void Main()
{
//Something...
}
}
class User
{
public int UserID { get; set; }
public string UserName { get; set; }
}
class MyCustomClass
{
User _user;
public MyCustomClass(User user)
{
_user = user;
}
public void Print()
{
Console.WriteLine(_user.UserName);
}
}
class MyProgram
{
public void StartNewScope(string username, int userid)
{ …Run Code Online (Sandbox Code Playgroud)