单例对象的实例未注入作用域实例化的对象中

时间:2019-01-13 18:24:28

标签: c# asp.net-core dependency-injection .net-core

我有以下两个课程:

public class MyScoped : IMyScoped
{
   private readonly ITransaction _transaction;

   public MyScoped(ITransaction transaction)
      => _transaction = transaction;

   public void Apply()
   {
     if(_transaction.Commit)
     {
        SaveToDatabase();
     }
   }
}

public class Transaction : ITransaction
{
   public bool Commit{get;set;}
}

我将这两个类连接起来:

services
 .AddSingleton<ITransaction,Transaction>()
 .AddScoped<IMyScoped,MyScoped>()

在调用MyScoped类的实例之前,我将“ Commit”设置为true,如以下代码所示:

_transaction.Commit = true;
_myScoped.Apply();

但是在检查false条件时始终为if(_transaction.Commit),因此事务未提交。我做错了什么?!

0 个答案:

没有答案