简体   繁体   中英

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

I'd like to use n-tier architecture with ASP.NET Core WebApi project. I defined some Repository with Interface in DAL layer (Class Library project). Then I'm trying to inject this by using IServiceCollection this way:

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

But this cannot be resolved. What I'm doing wrong here?

1_ Create One Class Library To Name Of OA.DataLayer

Download Microsoft.EntityFrameworkCore.SqlServer In Nuget

Create Your Models in DataLayer ForExample Tbl_Student

Create One class To Name Of DataContext And Copy This Code To Your class

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_Create One Class Libray To Name Of OA.Services

Create One interface To Name Of IRepository And Add This Code

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_Create One Class Libray To Name Of OA.Rep

Download Microsoft.EntityFrameworkCore.SqlServer In Nuget

Create One class To Name Of Repository Copy This Code

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_Create One Class Libray To Name Of OA.Business

Create One class To Name Of Student And Copy this Code

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

5_Go To Your Project Add appsetting.json And Copy This Code

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

Add This Code To startup

IConfiguration configuration;

To Your startup Add This Code To Method ConfigureServices

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

To Your Controller Add This Code

DataContext context;
Student student;

To Your constructor Add This Code

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

To Your Action Write This Code

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

Configure your Startup.cs:

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

Then, use like this in your API Controller:

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

Your Startup.cs seems OK, but I don't know how you're using your injected class, or, if you're getting some error message.

"RoleServico" is a class in a Class Library Project (like in your case). In my case I used "Singleton", but it's the same configuration for "Scoped".

*I was not able to comment your question and ask for more information (I don't have 50 reputation yet).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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