繁体   English   中英

ASP.NET核心。 如何与n层体系结构一起使用?

[英]ASP.NET Core. How to use with n-tier architecture?

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

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

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

1_创建一个Class Library的对名字OA.DataLayer

在Nuget中下载Microsoft.EntityFrameworkCore.SqlServer

在DataLayer中创建模型,例如Tbl_Student

创建一个class来命名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_以OA.Services的名称创建一个Class Libray

创建一个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.Rep

在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_以OA.Business的名称创建一个Class Libray

创建一个以学生姓名命名的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名声望)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM