Creating a new instance of the external class constructor with dependency injection

I am trying to use a sample application to test dependency injection. Before using DI, I have the following method in my class:

public IQueryable<BookDTO> GetBooks()
{
    var books = from b in db.Books
                select new BookDTO()
                {
                    Id = b.Id,
                    Title = b.Title,
                    AuthorName = b.Author.Name
                };

    return books;
}

      

BookDTO is a data transfer object defined in another project. Now I want to merge my projects freely. So I created the IDTOBase interface and made BookDTO implemented. I have a unity container where I have made the appropriate registration of the BookDTO class for IDTOBase.

But how can I rewrite the LINQ query in my original method? What will the "new BookDTO ()" replace?

thank

+3


source to share


3 answers


You start with the part of the answer that I think is "BookDTO - Data Transfer Object". As such, it makes little sense to abstract it as it relates to a very specific level in your application.

BookDTO plays the role of purely representing the data of the book (in some supposedly serializable form). This will happen at a low level in your application stack. Any code that requires the use of such data must create a Book domain object that can be used in the code. This decouples storing and retrieving book data (BookDTO) from its domain view (book).



Your interface definition I don't think it serves a purpose, so DI doesn't serve a purpose here. Where I feel DI comes into play is on the lookout for DTO books. The class that loads the book data will have such a service to be injected and used to retrieve the BookDTO instances.

+7


source


Well, whoever creates an object needs to know what actual type it will make.



It seems that you need some kind of repository that knows about IDTOBase

as well BookDTO

. Your application will know about IDTOBase

. The application will make a type call BookRepo.GetBooks

where your repository signature looks like IQueryable<IDTOBase> GetBooks

.

0


source


You need another class that can resolve the dependency for you.

In most DI cases, you say "Give me a" class "and allow any mapped interfaces it has for its mapped class instance," you need a "class".

I liked some of these examples as I studied DI. http://www.asp.net/web-api/overview/advanced/dependency-injection

0


source







All Articles