簡體   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