0

I have an ASP.Net Core project responsible for handling all web requests, and I have another project responsible for reading/writing from and into the database (Entity framework Core project). and of course another projects for different things but let's now imagine just we have only the previous two projects for the simplicity.

Is it possible some how to use ASP.Net Core dependency injection to inject classes into another projects (other projects which are library classes and not ASP.Net Core projects)? for example injecting DbContext to my Entity framework project?

5
  • Short answer is yes. have the projects depend on abstractions and have the composition root inject concrete implementations into the dependent projects. Commented Apr 1, 2017 at 12:38
  • @Nkosi Could you provide simple code for me please? I didn't understabd exactly what you mean. Commented Apr 1, 2017 at 12:46
  • Provide a minimal reproducible example that can be used to reproduce your current problem. This will aid in providing you with better answers, Commented Apr 1, 2017 at 12:48
  • You should also read up on the documentation learn.microsoft.com/en-us/aspnet/core/fundamentals/… Commented Apr 1, 2017 at 12:48
  • "Is it possible some how to use ASP.Net Core dependency injection to inject classes into another projects". What exactly is the problem you are having with this right now? Doing this should be trivial, because it works in the exact same way as you would register the classes from your ASP.NET project. Commented Apr 1, 2017 at 13:22

1 Answer 1

2

It may be that what you are thinking of doing is futile? If you are running inside an Asp.Net application, then all your code is probably called from a Controller, and the Controller can get all the dependencies you need, and pass them through:

public class MyController : Controller
{
    readonly MyComponent myComponent;

    public MyController(MyDbContext dbctx)
    {
        myComponent= new MyComponent(dbctx);
    }
    // ...etc...
}

But is one of your other projects a ConsoleApp or Service that runs outside the Asp.Net application? Then the question is, can I reference Asp.Net.Core to use DI outside of Asp.Net?

I suspect the answer is 'probably-yes', and your starting point would be to copy MS's builder code on github.

But that would beg the question, of why choose the Asp.Net DI over all the existing DI containers out there? Castle.Windsor, AutoFac, StructureMap, Ninject have all done the job well for years.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.