ASP.NET Core - Dependency Injection


My controller:

    [Route("api/[controller]")]
    [ApiController]
    public class CategoriesController : ControllerBase
    {
        private readonly IUnitOfWork unitOfWork;

        public CategoriesController(IUnitOfWork unitOfWork)
        {
            this.unitOfWork = unitOfWork;
        }

        [HttpGet]
        [Route("TestCategories")]
        public ActionResult<IEnumerable<Category>> TestCategories()
        {
            return unitOfWork.Categories.FindAll().ToList();
        }
    }

My Startup:

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ClassifiedAdsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddScoped<IUnitOfWork, UnitOfWork>();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

I did break my app so i can understand how the codes work.

As you can see on my controller i used IUnitOfWork (Interface that comes from MyProject.Domain - class library) 

Scenario:

  1. if i use the UnitOfWork class, the only thing the i need to inject (to startup.cs) is the UnitOfWork class only.
  2. if i use the IUnitOfWork interface. i need to inject both (to startup.cs) IUnitOfWork interface and UnitOfWork class as well because it gives error see below.

What i know was class library has no composition root, thats why you need to inject them to the application that uses it.

My question is:

1. What is the difference of using UnitOfWork (Class that comes from MyProject.Data - class library) vs IUnitOfWork?

2. Why they often use interface(base) when doing dependency injection in constructor instead of class.

3. How IUnitOfWork works like class even its interface (interface is only declaration why it gives me implementation), as i run the api it gives me the result i wanted, but im wondering how interface has implementation based on my given example.

PS: I have read the articles from the internet (I believe, was I read articles were not enough regarding to this matter) and also microsoft documentation regarding dependency injection, but im still confused how it works, does IUnitOfWork converted to UnitOfWork.

Hoping to enlighthen me.

Sorry for my long post.

Happy Coding!


Asked by:- EmmanuelReal
0
: 2086 At:- 7/6/2018 1:37:17 PM
ASP.NET Dependency Injection







1 Answers
profileImage Answered by:- vikas_jk

1. What is the difference of using UnitOfWork (Class that comes from MyProject.Data - class library) vs IUnitOfWork?

-> UnitOfWork is class with methods defined in it while IUnitofWork is interface like below

public interface IUnitOfWork
{
    IGenericRepository<Blog> BlogRepository { get; }
    IGenericRepository<Post> PostRepository { get; }
    void Save();
}

UnitOfWork Class

public class UnitOfWork : IUnitOfWork
{
    private readonly BloggingContext _bloggingContext;
    private IGenericRepository<Blog> _blogRepository;
    private IGenericRepository<Post> _postRepository;
    public UnitOfWork(BloggingContext bloggingContext)
    {
        _bloggingContext = bloggingContext;
    }

    public IGenericRepository<Blog> BlogRepository
    {
        get
        {
            return _blogRepository = _blogRepository ?? new GenericRepository<Blog>(_bloggingContext);
        }
    }

    public IGenericRepository<Post> PostRepository
    {
        get
        {
            return _postRepository = _postRepository ?? new GenericRepository<Post>(_bloggingContext);
        }
    }

    public void Save()
    {
        _bloggingContext.SaveChanges();
    }
}

2. Why they often use interface(base) when doing dependency injection in constructor instead of class.

-> May be you are referring this line of code in configuration services

services.AddScoped<IUnitOfWork, UnitOfWork>();

Here we are actually registering the services for UnitOfWork which we have created using above class and Interface, to know more details about it, read this

https://stackoverflow.com/questions/38138100/what-is-the-difference-between-services-addtransient-service-addscope-and-servi

3. How IUnitOfWork works like class even its interface (interface is only declaration why it gives me implementation), as i run the api it gives me the result i wanted, but im wondering how interface has implementation based on my given example.

-> You are missing some info here, only IUnitOfWork cannot provide your implementation, I cannot say what you have missed without complete project code, but you are right IUnitOfWork cannot provide you complete implementaion it is just interface.

0
At:- 7/6/2018 3:31:28 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use