4 ms·
Not having used .NET recently, is what they've implemented something like Spring? The description of DI everywhere and inscrutable failures at run-time remind
by ThrowawayR2 6y ago
Not having used .NET recently, is what they've implemented something like Spring? The description of DI everywhere and inscrutable failures at run-time remind me of that.
- chunkyfunky 6y agoNot sure how Spring does it, but for example in ASP.Net Core, it's really simple. In the app startup class there is a method that's automatically called by the framework whereby it supplies a services container. In this method you "wire up" your interface->concrete mappings public void ConfigureServices(IServiceCollection services) { services.AddScoped<IMyDependency, MyDependency>(); } Later on when for e.g. an APIController is instantiated, once you've declare a constructor dependency on IMyDependency, it gets resolved for you automatically and whatever concrete class is mapped to gets created and passed to the constructor. Outside of ASP.Net (console app for example) you can either do this manually, or you can get a ServiceCollection object from the framework, or you ca nuse a 3rd party DI library, etc. Generally speaking if you don't configure this correctly you get a pretty simple message telling you that the container could not service the request for an IMyDependency or whatever and then it's pretty simple to figure out what you missed in the wire-up.
- bebop 6y agoIf you understand Spring then Asp.net Core will feel right at home. I think .Net tends to be more explicit in the configuration, with DI being no exception. For instance, in Spring you can just annotate a service with @Service and the DI framework will pick that up. In Asp.net Core, you actually have to say IThing is backed by Thing as a singleton when running the application and TestThing when running tests. Edit: Also as others have noted, constructor injection is the way to do DI.