Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# NET内核。如何使用n层体系结构?_C#_Asp.net_Asp.net Core - Fatal编程技术网

C# NET内核。如何使用n层体系结构?

C# NET内核。如何使用n层体系结构?,c#,asp.net,asp.net-core,C#,Asp.net,Asp.net Core,我想在ASP.NET核心WebApi项目中使用n层体系结构。我在DAL层(类库项目)中定义了一些具有接口的存储库。然后,我尝试通过使用IServiceCollection以这种方式注入它: public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc();

我想在ASP.NET核心WebApi项目中使用n层体系结构。我在DAL层(类库项目)中定义了一些具有接口的存储库。然后,我尝试通过使用IServiceCollection以这种方式注入它:

       public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            services.AddScoped<IUsersRepository, UsersRepository>();
        }
public void配置服务(IServiceCollection服务)
{
//添加框架服务。
services.AddMvc();
services.addScope();
}

但这是无法解决的。我做错了什么?

配置您的Startup.cs:

public void ConfigureServices(IServiceCollection services) {
...
  services.AddSingleton<ISessionFactory>(c => {
    var config = new Configuration();
    ...
    return config.BuildSessionFactory();
  });
...
  services.AddSingleton<RoleServico>();
...
}
public void配置服务(IServiceCollection服务){
...
services.AddSingleton(c=>{
var config=新配置();
...
返回config.BuildSessionFactory();
});
...
services.AddSingleton();
...
}
然后,在API控制器中使用如下方法:

[Route("api/role")]
public class RoleController : Controller {

    private readonly ISessionFactory SessionFactory;
    private readonly RoleServico RoleServico;

    public RoleController(ISessionFactory sessionFactory, RoleServico roleServico) {
      if (sessionFactory == null)
        throw new ArgumentNullException("sessionFactory");
      SessionFactory = sessionFactory;
      this.RoleServico = roleServico;
    }

    [HttpGet]
    public IList<RoleModel> Get() {
      IList<RoleModel> model = new List<RoleModel>();
      using (var session = SessionFactory.OpenSession())
      using (var transaction = session.BeginTransaction()) {
        return RoleServico.SelecionarRoles(session);
      }
    }
}
[路由(“api/角色”)]
公共类角色控制器:控制器{
私有只读ISessionFactory SessionFactory;
私人只读RoleServico RoleServico;
公共角色控制器(ISessionFactory sessionFactory、RoleServico RoleServico){
if(sessionFactory==null)
抛出新的ArgumentNullException(“sessionFactory”);
SessionFactory=SessionFactory;
this.RoleServico=RoleServico;
}
[HttpGet]
公共IList Get(){
IList模型=新列表();
使用(var session=SessionFactory.OpenSession())
使用(var transaction=session.BeginTransaction()){
返回RoleServico.SelecionarRoles(会话);
}
}
}
你的Startup.cs看起来不错,但我不知道你是如何使用你的注入类的,或者,如果你收到一些错误消息

“RoleServico”是类库项目中的一个类(与您的案例类似)。在我的例子中,我使用了“Singleton”,但“Scoped”的配置是相同的


*我无法评论您的问题并询问更多信息(我还没有50%的声誉)。

配置您的Startup.cs:

public void ConfigureServices(IServiceCollection services) {
...
  services.AddSingleton<ISessionFactory>(c => {
    var config = new Configuration();
    ...
    return config.BuildSessionFactory();
  });
...
  services.AddSingleton<RoleServico>();
...
}
public void配置服务(IServiceCollection服务){
...
services.AddSingleton(c=>{
var config=新配置();
...
返回config.BuildSessionFactory();
});
...
services.AddSingleton();
...
}
然后,在API控制器中使用如下方法:

[Route("api/role")]
public class RoleController : Controller {

    private readonly ISessionFactory SessionFactory;
    private readonly RoleServico RoleServico;

    public RoleController(ISessionFactory sessionFactory, RoleServico roleServico) {
      if (sessionFactory == null)
        throw new ArgumentNullException("sessionFactory");
      SessionFactory = sessionFactory;
      this.RoleServico = roleServico;
    }

    [HttpGet]
    public IList<RoleModel> Get() {
      IList<RoleModel> model = new List<RoleModel>();
      using (var session = SessionFactory.OpenSession())
      using (var transaction = session.BeginTransaction()) {
        return RoleServico.SelecionarRoles(session);
      }
    }
}
[路由(“api/角色”)]
公共类角色控制器:控制器{
私有只读ISessionFactory SessionFactory;
私人只读RoleServico RoleServico;
公共角色控制器(ISessionFactory sessionFactory、RoleServico RoleServico){
if(sessionFactory==null)
抛出新的ArgumentNullException(“sessionFactory”);
SessionFactory=SessionFactory;
this.RoleServico=RoleServico;
}
[HttpGet]
公共IList Get(){
IList模型=新列表();
使用(var session=SessionFactory.OpenSession())
使用(var transaction=session.BeginTransaction()){
返回RoleServico.SelecionarRoles(会话);
}
}
}
你的Startup.cs看起来不错,但我不知道你是如何使用你的注入类的,或者,如果你收到一些错误消息

“RoleServico”是类库项目中的一个类(与您的案例类似)。在我的例子中,我使用了“Singleton”,但“Scoped”的配置是相同的


*我无法评论您的问题并询问更多信息(我还没有50个声誉)。

1\u创建一个
类库,以OA.DataLayer的名称命名

在Nuget中下载Microsoft.EntityFrameworkCore.SqlServer

在数据层中创建模型示例
Tbl\u Student

为DataContext的名称创建一个
,并将此代码复制到类中

public class DataContext:DbContext
    {
        public DataContext(DbContextOptions<DataContext> options):base(options)
        {
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public virtual DbSet<Tbl_Student> Tbl_Students { get; set; }

    } 
3\u创建一个
类库
到OA.Rep的名称

在Nuget中下载Microsoft.EntityFrameworkCore.SqlServer

创建一个
class
到存储库名称复制此代码

public interface IRepository<T> where T : class
    {
        Task<T> GetByIdAsync(int id);
        IQueryable<T> GetAll();
        void Remove(T entity);
        void Add(T entity);
        void Update(T entity);
        Task<int> SaveChangeAsync();
    }
public class Repository<T> : IRepository<T> where T : class
    {
        DataContext context;
        DbSet<T> db;
        public Repository(DataContext context)
        {
            this.context = context;
            db = context.Set<T>();

        }
        public void Add(T entity)
        {
            db.Add(entity);
        }

        public IQueryable<T> GetAll()
        {
            return db;
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await Task<T>.Run(() =>
            {
                return db.FindAsync(1);
            });
        }

        public void Remove(T entity)
        {
            db.Remove(entity);
        }

        public async Task<int> SaveChangeAsync()
        {
            return await Task<T>.Run(() =>
            {
                return context.SaveChangesAsync();
            });
        }

        public void Update(T entity)
        {
            context.Entry<T>(entity).State = EntityState.Modified;
        }
    }
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=dh;Integrated Security=True;"
  }
}
DataContext context;
Student student;
public HomeController(DataContext context)
        {
            this.context = context;
            student = new Student(context);
        }
  public async Task<IActionResult> Index()
        {
            var q = await student.GetByIdAsync(1);
            return View();
        }
5_转到您的项目添加
appsetting.json
并复制此代码

public interface IRepository<T> where T : class
    {
        Task<T> GetByIdAsync(int id);
        IQueryable<T> GetAll();
        void Remove(T entity);
        void Add(T entity);
        void Update(T entity);
        Task<int> SaveChangeAsync();
    }
public class Repository<T> : IRepository<T> where T : class
    {
        DataContext context;
        DbSet<T> db;
        public Repository(DataContext context)
        {
            this.context = context;
            db = context.Set<T>();

        }
        public void Add(T entity)
        {
            db.Add(entity);
        }

        public IQueryable<T> GetAll()
        {
            return db;
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await Task<T>.Run(() =>
            {
                return db.FindAsync(1);
            });
        }

        public void Remove(T entity)
        {
            db.Remove(entity);
        }

        public async Task<int> SaveChangeAsync()
        {
            return await Task<T>.Run(() =>
            {
                return context.SaveChangesAsync();
            });
        }

        public void Update(T entity)
        {
            context.Entry<T>(entity).State = EntityState.Modified;
        }
    }
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=dh;Integrated Security=True;"
  }
}
DataContext context;
Student student;
public HomeController(DataContext context)
        {
            this.context = context;
            student = new Student(context);
        }
  public async Task<IActionResult> Index()
        {
            var q = await student.GetByIdAsync(1);
            return View();
        }
将此代码添加到启动

IConfiguration configuration;
将此代码添加到方法ConfigureServices

services.AddDbContext<DataContext>(options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
将此代码添加到
构造函数中

public interface IRepository<T> where T : class
    {
        Task<T> GetByIdAsync(int id);
        IQueryable<T> GetAll();
        void Remove(T entity);
        void Add(T entity);
        void Update(T entity);
        Task<int> SaveChangeAsync();
    }
public class Repository<T> : IRepository<T> where T : class
    {
        DataContext context;
        DbSet<T> db;
        public Repository(DataContext context)
        {
            this.context = context;
            db = context.Set<T>();

        }
        public void Add(T entity)
        {
            db.Add(entity);
        }

        public IQueryable<T> GetAll()
        {
            return db;
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await Task<T>.Run(() =>
            {
                return db.FindAsync(1);
            });
        }

        public void Remove(T entity)
        {
            db.Remove(entity);
        }

        public async Task<int> SaveChangeAsync()
        {
            return await Task<T>.Run(() =>
            {
                return context.SaveChangesAsync();
            });
        }

        public void Update(T entity)
        {
            context.Entry<T>(entity).State = EntityState.Modified;
        }
    }
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=dh;Integrated Security=True;"
  }
}
DataContext context;
Student student;
public HomeController(DataContext context)
        {
            this.context = context;
            student = new Student(context);
        }
  public async Task<IActionResult> Index()
        {
            var q = await student.GetByIdAsync(1);
            return View();
        }
要执行
操作
请编写此代码

public interface IRepository<T> where T : class
    {
        Task<T> GetByIdAsync(int id);
        IQueryable<T> GetAll();
        void Remove(T entity);
        void Add(T entity);
        void Update(T entity);
        Task<int> SaveChangeAsync();
    }
public class Repository<T> : IRepository<T> where T : class
    {
        DataContext context;
        DbSet<T> db;
        public Repository(DataContext context)
        {
            this.context = context;
            db = context.Set<T>();

        }
        public void Add(T entity)
        {
            db.Add(entity);
        }

        public IQueryable<T> GetAll()
        {
            return db;
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await Task<T>.Run(() =>
            {
                return db.FindAsync(1);
            });
        }

        public void Remove(T entity)
        {
            db.Remove(entity);
        }

        public async Task<int> SaveChangeAsync()
        {
            return await Task<T>.Run(() =>
            {
                return context.SaveChangesAsync();
            });
        }

        public void Update(T entity)
        {
            context.Entry<T>(entity).State = EntityState.Modified;
        }
    }
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=dh;Integrated Security=True;"
  }
}
DataContext context;
Student student;
public HomeController(DataContext context)
        {
            this.context = context;
            student = new Student(context);
        }
  public async Task<IActionResult> Index()
        {
            var q = await student.GetByIdAsync(1);
            return View();
        }
公共异步任务索引()
{
var q=等待学生.GetByIdAsync(1);
返回视图();
}

1\为OA.DataLayer的名称创建一个
类库

在Nuget中下载Microsoft.EntityFrameworkCore.SqlServer

在数据层中创建模型示例
Tbl\u Student

为DataContext的名称创建一个
,并将此代码复制到类中

public class DataContext:DbContext
    {
        public DataContext(DbContextOptions<DataContext> options):base(options)
        {
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public virtual DbSet<Tbl_Student> Tbl_Students { get; set; }

    } 
3\u创建一个
类库
到OA.Rep的名称

在Nuget中下载Microsoft.EntityFrameworkCore.SqlServer

创建一个
class
到存储库名称复制此代码

public interface IRepository<T> where T : class
    {
        Task<T> GetByIdAsync(int id);
        IQueryable<T> GetAll();
        void Remove(T entity);
        void Add(T entity);
        void Update(T entity);
        Task<int> SaveChangeAsync();
    }
public class Repository<T> : IRepository<T> where T : class
    {
        DataContext context;
        DbSet<T> db;
        public Repository(DataContext context)
        {
            this.context = context;
            db = context.Set<T>();

        }
        public void Add(T entity)
        {
            db.Add(entity);
        }

        public IQueryable<T> GetAll()
        {
            return db;
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await Task<T>.Run(() =>
            {
                return db.FindAsync(1);
            });
        }

        public void Remove(T entity)
        {
            db.Remove(entity);
        }

        public async Task<int> SaveChangeAsync()
        {
            return await Task<T>.Run(() =>
            {
                return context.SaveChangesAsync();
            });
        }

        public void Update(T entity)
        {
            context.Entry<T>(entity).State = EntityState.Modified;
        }
    }
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=dh;Integrated Security=True;"
  }
}
DataContext context;
Student student;
public HomeController(DataContext context)
        {
            this.context = context;
            student = new Student(context);
        }
  public async Task<IActionResult> Index()
        {
            var q = await student.GetByIdAsync(1);
            return View();
        }
5_转到您的项目添加
appsetting.json
并复制此代码

public interface IRepository<T> where T : class
    {
        Task<T> GetByIdAsync(int id);
        IQueryable<T> GetAll();
        void Remove(T entity);
        void Add(T entity);
        void Update(T entity);
        Task<int> SaveChangeAsync();
    }
public class Repository<T> : IRepository<T> where T : class
    {
        DataContext context;
        DbSet<T> db;
        public Repository(DataContext context)
        {
            this.context = context;
            db = context.Set<T>();

        }
        public void Add(T entity)
        {
            db.Add(entity);
        }

        public IQueryable<T> GetAll()
        {
            return db;
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await Task<T>.Run(() =>
            {
                return db.FindAsync(1);
            });
        }

        public void Remove(T entity)
        {
            db.Remove(entity);
        }

        public async Task<int> SaveChangeAsync()
        {
            return await Task<T>.Run(() =>
            {
                return context.SaveChangesAsync();
            });
        }

        public void Update(T entity)
        {
            context.Entry<T>(entity).State = EntityState.Modified;
        }
    }
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=dh;Integrated Security=True;"
  }
}
DataContext context;
Student student;
public HomeController(DataContext context)
        {
            this.context = context;
            student = new Student(context);
        }
  public async Task<IActionResult> Index()
        {
            var q = await student.GetByIdAsync(1);
            return View();
        }
将此代码添加到启动

IConfiguration configuration;
将此代码添加到方法ConfigureServices

services.AddDbContext<DataContext>(options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
将此代码添加到
构造函数中

public interface IRepository<T> where T : class
    {
        Task<T> GetByIdAsync(int id);
        IQueryable<T> GetAll();
        void Remove(T entity);
        void Add(T entity);
        void Update(T entity);
        Task<int> SaveChangeAsync();
    }
public class Repository<T> : IRepository<T> where T : class
    {
        DataContext context;
        DbSet<T> db;
        public Repository(DataContext context)
        {
            this.context = context;
            db = context.Set<T>();

        }
        public void Add(T entity)
        {
            db.Add(entity);
        }

        public IQueryable<T> GetAll()
        {
            return db;
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await Task<T>.Run(() =>
            {
                return db.FindAsync(1);
            });
        }

        public void Remove(T entity)
        {
            db.Remove(entity);
        }

        public async Task<int> SaveChangeAsync()
        {
            return await Task<T>.Run(() =>
            {
                return context.SaveChangesAsync();
            });
        }

        public void Update(T entity)
        {
            context.Entry<T>(entity).State = EntityState.Modified;
        }
    }
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=dh;Integrated Security=True;"
  }
}
DataContext context;
Student student;
public HomeController(DataContext context)
        {
            this.context = context;
            student = new Student(context);
        }
  public async Task<IActionResult> Index()
        {
            var q = await student.GetByIdAsync(1);
            return View();
        }
要执行
操作
请编写此代码

public interface IRepository<T> where T : class
    {
        Task<T> GetByIdAsync(int id);
        IQueryable<T> GetAll();
        void Remove(T entity);
        void Add(T entity);
        void Update(T entity);
        Task<int> SaveChangeAsync();
    }
public class Repository<T> : IRepository<T> where T : class
    {
        DataContext context;
        DbSet<T> db;
        public Repository(DataContext context)
        {
            this.context = context;
            db = context.Set<T>();

        }
        public void Add(T entity)
        {
            db.Add(entity);
        }

        public IQueryable<T> GetAll()
        {
            return db;
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await Task<T>.Run(() =>
            {
                return db.FindAsync(1);
            });
        }

        public void Remove(T entity)
        {
            db.Remove(entity);
        }

        public async Task<int> SaveChangeAsync()
        {
            return await Task<T>.Run(() =>
            {
                return context.SaveChangesAsync();
            });
        }

        public void Update(T entity)
        {
            context.Entry<T>(entity).State = EntityState.Modified;
        }
    }
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=dh;Integrated Security=True;"
  }
}
DataContext context;
Student student;
public HomeController(DataContext context)
        {
            this.context = context;
            student = new Student(context);
        }
  public async Task<IActionResult> Index()
        {
            var q = await student.GetByIdAsync(1);
            return View();
        }
公共异步任务索引()
{
var q=等待学生.GetByIdAsync(1);
返回视图();
}

您的用户订阅本身是否需要依赖项,而该依赖项尚未注册?您应该能够得到一条错误消息,帮助您指出这一点。@MikeD,此回购协议中没有新内容。我以前创建过很多次它,和以前一样,我希望Repo实例应该用DI容器注入控制器。通常Repo采用dbContext类型的对象,您确定您的Repo在其自己的构造函数中没有任何参数吗?@MikeD,绝对-只有空的实体。是否有错误消息?您的UsersRepo本身是否需要依赖项,并且该依赖项尚未注册?你应该能做到