ASP.NET核心.如何与n层架构一起使用

本文关键字:一起 核心 NET ASP | 更新日期: 2023-09-27 18:06:25

我想在ASP.NET Core WebApi项目中使用n层架构。我在DAL层定义了一些带有接口的存储库(类库项目(。然后我尝试通过以下方式使用IServiceCollection注入:

       public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            services.AddScoped<IUsersRepository, UsersRepository>();
        }

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

ASP.NET核心.如何与n层架构一起使用

1_创建一个Class Library到OA.DataLayer 的名称

在Nuget 中下载Microsoft.EntityFrameworkCore.SqlServer

在数据层中为示例Tbl_Student 创建模型

创建一个class To Name Of 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; }
    } 

2_创建一个Class Libray到OA.Services 的名称

创建一个interface到IRepository的名称并添加此代码

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();
    }

3_创建一个Class Libray到OA的名称。代表

在Nuget 中下载Microsoft.EntityFrameworkCore.SqlServer

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

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;
        }
    }

4_创建一个Class Libray到OA的名称。业务

创建一个class以学生的名义并复制此代码

public class Student:Repository<Tbl_Student>
    {
        DataContext context;
        public Student(DataContext context):base(context)
        {
            this.context = context;
        }
    }

5_转到您的项目添加appsetting.json并复制此代码

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=dh;Integrated Security=True;"
  }
}

将此代码添加到startup

IConfiguration configuration;

添加此代码到方法ConfigureServices

services.AddDbContext<DataContext>(options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

将此代码添加到您的Controller

DataContext context;
Student student;

将此代码添加到您的constructor

public HomeController(DataContext context)
        {
            this.context = context;
            student = new Student(context);
        }

给你的Action写这个代码

  public async Task<IActionResult> Index()
        {
            var q = await student.GetByIdAsync(1);
            return View();
        }

配置您的Startup.cs:

public void ConfigureServices(IServiceCollection services) {
...
  services.AddSingleton<ISessionFactory>(c => {
    var config = new Configuration();
    ...
    return config.BuildSessionFactory();
  });
...
  services.AddSingleton<RoleServico>();
...
}

然后,像这样在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);
      }
    }
}

你的Startup.cs看起来还可以,但我不知道你是如何使用注入的类的,或者,如果你收到一些错误消息。

"RoleServico"是类库项目中的一个类(就像您的情况一样(。在我的案例中,我使用了"Singleton",但它与"Scoped"的配置相同。

*我无法评论你的问题,也无法询问更多信息(我还没有50的声誉(。