by christophilus · 6y ago · 0 comments
So, what’s the best-organized resource for getting up to speed on .NET these days?
Then it's just a massive waste of time and gets in the way.
I really feel that you (and Microsoft) have completely lost sight of the reason why DI was ever even necessary and have become blind to just how much extra code it generates. The only reason was to inject mocks, and people hand-wrung for ages over it because the code to do so infects all the other code. Then people started to try and back justify it with IoC, but it's never really been a convincing argument.
It's also something that if you're not working regularly with it can be very mysterious and when it fails, fails at run-time, quite inscrutably sometimes.
From my perspective it's just boilerplate magic that if you actually need it, fair enough, but if you don't is a persistent, nagging, pain in the ass.
In C# the idiomatic way to achieve this is via constructor injection, which is made much easier to manage in ASP.Net with a DI library that works with the framework for you (either the built in one or AutoFac / SimpleInjector, etc.). But you don't have to use a library; many times I'm writing a simple-ish console app and just use good old "Poor Man's DI" where I manually construct my object graphs at startup.
DIP is achieved precisely when the components (be they packages, projects, classes, types) are organized with the low-level modules depending on the high-level modules rather than vice versa. In English, this usually means the I/O and any heavy framework code is kept out of the program logic.
What DI does do is confuse this matter. Class relationships which are mere IMPLEMENTATION DETAILS of a module are elevated alongside the actual component architecture of the program. The object graph becomes obscured. Program execution order becomes nondeterministic. The callstack is completely ruined, undoing decades of enlightenment since Dijkstra's "GOTO statement considered harmful." And all my experience with the pattern proves, the DI container causes programmers to not even evaluate or understand whether their dependencies are even inverted, because all classes and their relationships just become one amorphous blob floating aimlessly inside the container.
1) that graph of object creation is NOT equal to graph of object usage
2) if you don't use DI, problems won't automagically go away - code will _still_ have dependencies, just they'll be hidden and tightly coupled
You can still depend on abstractions without DI. Just use an interface or asbtract class in your code.
DI only plays into how you acquire yourself an instance of the concrete class for that abstraction you depend on.
So it can be given to you by your caller (DI). You can go fetch it somewhere (ServiceLocator). You can create it through a utility (Factory). Or you can create it yourself old fashion way with new.
> But you don't have to use a library; many times I'm writing a simple-ish console app and just use good old "Poor Man's DI" where I manually construct my object graphs at startup
I will support that. I'd like people to be precise in their criticism, do you find the DI pattern troublesome, or some particular DI framework?
I am not sure what is a better way to solve this problem, but the original OP is right - it's far too much ceremony.
The main thing holding C# back is the culture around the DI and weird hostbuilder code associated with ASPNET. If you just skip that part, it's great. Unfortunately a lot of web examples, solutions, and code libraries themselves are ASPNET-focused, and more and more of the code becomes some truly bizarre, unreadable framework injection in an inside-out fluent builder.
I find it very useful for several purposes that have nothing to do with mocking or testing.
> and have become blind to just how much extra code it generates
It doesn’t generate any extra code at all.
For the record, I think that built-in .NET DI is pretty bad. It would be better if they managed to avoid including that abstraction in the framework, even if I personally choose to use DI in most of my projects.
When I think DI, I think: //Startup.cs has all the config "goo" I don't want to repeat elsewhere.
services.AddDbContext<MyDbContext>(o=>o.UseSqlServer(config.GetConnectionString("foo"));
services.AddTransient<MyService>();
//MyController.cs (or Page, etc) and others get to use it with no ceremony:
public MyController(MyService foo){ this.foo = foo; }
vs no DI, where the config "goo" has to be repeated in every place I intend to use it (or in this case it could also be buried in MyService.cs):
public MyController(){this.foo = new MyService(new MyDbContext(ConfigurationManager.GetConnectionString("foo")));}
public Dispose(){this.foo.Dispose();}
If I knew MyService would never be swapped out and only ever used in one place, I may opt for the no-DI route. I'll often start there then move it to DI when I want testability, reuse of config, plugability, etc..
The method could return a MyService, or an IMyService if you want to be more flexible. It can always create a fresh object, manage and return a singleton object, or manage a pool of objects. For the new and pool cases, you can have another static method for 'returning' the object when the controller/page is done with it, so you can manage disposal or pool availability.
The biggest advantage I see to this approach is in debugging: there is a clear stack trace back to the source of the object, and also to its implementation if you're not using an interface. With DI you often can't tell where an object came from, and sometimes it takes some digging to even find out its exact type (unless you only have one implementation of each interface, which is often the case.)
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.
Edit: Also as others have noted, constructor injection is the way to do DI.
For our multi-tiered system, this means managing caching and logging of certain calls and events at the level of data access. And at the service level, it means dealing with things like authorisation.
Smart use of DI sets the system up in a way were it's easy to handle these types of cross-cutting concerns where appropriate, and with minimal boilerplate. It also simplifies refactoring.
Do you just want to `new SomeClass()` instead? If so, what's stopping you from just doing that?
Duh! Then how’d you wire up interfaces with implementation aka constructor injection?
A massive waste of time? Adding a constructor and one line to startup.cs is a massive waste of time? Just how long does it take you?
> It's also something that if you're not working regularly with it can be very mysterious and when it fails, fails at run-time, quite inscrutably sometimes.
If DI fails it’s usually just because you’ve forgotten to add that one line to the startup.cs, and the error you get will tell you that. Can you give me a concrete example of how DI is inscrutable?
Passing required dependencies by constructors makes this extremely apparent, not just to the DI framework but to the developers themselves. With constructor injection I can immediately grasp exactly what dependencies an object depends on without even going into the full code flow to look at all the code to find all the IOC container calls.
Edit: Also constructor injection is critical for testing dependency injection. IT allows you to have automated tests that construct every relevant object using the same DI setup as your live application and you can verify that the DI framework can resolve dependencies for everything.
If your DI is lazily done this cannot happen unless you explicitly call all code flows, opening yourself up to runtime errors that may be missed. Unit tests won't catch this because the dependencies of your production site will be different than the dependencies of your test scenarios.
(https://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Patt...)
Personally, I quite like that quite a bit compared to platforms and frameworks where the convention seems instead to be, "RTFM or die (at run time)."
Except in Windows Forms, where the norm is a zero-argument constructor and setting everything via properties, because that approach works with component-based design-time tools. Come to think of it, I think WPF and its descendants do the same.
I've actually worked with C# for over 15 years now and written apps with (in order of age) VBScript, webforms, web services (the MS SOAP stuff), MVC 1, MVC 2, MVC 3, MVC 4, Web API, Web API 2, the OData one I forget the name of and asp.net core. Oh and Silverlight. I've probably missed something. On yeah, WCF. And even WWF! Basically EVERYTHING web-related to C#. Plus enough work in PHP, Python, Ruby, Express, etc. to be able to compare different approaches. And even sometimes VB.net, I've maintained and then migrated entire code-bases from that to C#.
I'm not entirely sure what more familiarity I need?
I'd also note that there are a lot of other people agreeing with my in that thread, almost all of whom show a decent technical understanding. And it's got a lot of upvotes.
But, even if I "misunderstood" or have a "lack of familiarity", that speaks of how poor the design/documentation actually is. If you can so easily shoot yourself in the foot with it, it's not fit for purpose.
WebHost.CreateDefaultBuilder().Configure(app =>
{
app.UseRouting();
app.UseEndpoints(e =>
{
e.MapGet("/", c => c.Response.WriteAsync("Hello world!"));
e.MapGet("hello/{name}", c => c.Response.WriteAsync($"Hello, {c.Request.RouteValues["name"]}"));
});
}).Build().Run();
I also stumble over that once in a while but I have no hard feeling on it.https://github.com/davidfowl/Todos/blob/master/TodoBasic/Pro...
I recently ran through the entire ecosystem thinking that there must be something akin to Sinatra (micro web framework) in .Net. Nope. Every single thing is built on top of ASP .net.
I did find a WIP library where they are trying to go for a low ceremony framework https://github.com/featherhttp/framework, but even that is built on top of ASP .net
For me the worst bit about .Net is their treatment of F#. IMO, it is one of the most practical and usable functional languages out there. But none of the official docs have anything on F# at all. Here is an example doc; see if you can find any code example for F#. https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor...
Its always C#. And I have 0 interest in that kitchen sink language.
Between ASP.Net and C# being the entire world for .Net, I have really not much interest in using it for anything. There are plentiful of interesting languages and ecosystems that I can use for my small time projects.
I agree that the ASP.NET documentation is lacking in F# code samples (although the example you picked is a bad one as Razor doesn't support F#, and so naturally wouldn't have F# code samples). You might find that Giraffe is a more comfortable framework, as it's essentially an F#-ified shim on top of ASP.NET.
To me it's usually a synonym to the full-fat MVC with controllers, DI, everything. This is reinforced by most of the dotnet templates and documentation, which make it feel like if you ask for a banana you're given a gorilla and the entire forest whether you want it or not.
In comparison, if you look at Go you'll see the "net/http" package. It's the HTTP server. Extendable. Built in - not something to download from NuGet. Only does HTTP - not reinventing its own DI, configuration management, IIS, etc.
.NET supports as much ceremony as you want to deal with.
This is only true in theory, but couldn't be further away in reality.
Microsoft suffocates everything which is not built in-house 1), so there is absolutely no OSS ecosystem going on in .NET which would allow a choice of different non-ASP.NET web frameworks.
Other languages have a wealth of different web frameworks and some are super basic and lightweight and others are huge with batteries included.
You don't get that in .NET at all. Everything is ASP.NET Core, and ASP.NET Core is a typical Microsoft product - an attempt to build a one size fits all solution, the magic silver bullet to solve everyone's problems at once. Like with all silver bullets, when trying to please everybody you end up pleasing nobody.
1) Except F#. In F# you will find a more vibrant OSS community and non ASP.NET alternatives (most famously Suave), but only because Microsoft doesn't care about F#. Instead of creating an equal level playing field for C# and F# they are morphing C# into an F# hybrid and eventually will stop caring about F# even more than now.
ASP.NET is not a single monolithic thing, the Core evolution has made everything modular and you can plug and play the parts you want. You can use just routing to translate URLs to endpoints, or just the view engine, or just the serialization bindings, or just razor pages, or just MVC, or just low-level HTTP responses, or just GRPC, or anything else. The entire pipeline is a series of middleware, which itself layered on the Kestrel webserver, which itself is layered on low-level sockets wrapped with Pipelines and Memory APIs.
There is no one-size fits all, and asp.net explicitly recognizes and solves for it. The issue might be your expectation that there is a small/light and large/heavy framework. There isn't, you just make one to fit you.
It's probably a cover your ass situation, especially at the larger, more conservative, enterprise-y, non-tech companies .NET is frequently used at. No middle manager would get fired for suggesting to use a Microsoft developed & endorsed solution instead of using some hipster open source framework.
For ex, AFAIK, there was no community participation on DI Design and community feedback on DI design was rejected. Then it was made the default in ASP.NET.
https://blog.simpleinjector.org/2016/06/whats-wrong-with-the...
If your view of low ceremony is matching HTTP verbs to methods, you may happily code your own against the HTTP primitives; if you want a framework that abstracts the complexity and provides a shiny-happy path, you may have to allow for some ceremony. The tooling is the antidote to this.
I think the place you trip up here is in not wanting to use a batteries included approach, while using a framework that makes the necessary abstraction/complexity tradeoffs for projects of mid to large scale. The appropriate tradeoffs _cannot_ be one size fits all.
F#'s support is tricky, as the number of users here is dwarfed by those in C#; and although .NET supports this language diversity, there are no direct idiomatic 'conversions' possible between C# and F# in many cases. This multiplies the effort of providing documentation and examples. I too would like to see it treated as a first class citizen, and for that - the code is OSS.
You have hit the core of my issue here. I am more used to the node-express or golang's way of working where you start off with the smallest and simplest scaffolding and then add on the bits that you need. Rails and ASP .Net are not something I want to use for my small time projects.
Its probably unreasonable for me to expect .Net to be something completely different from what it really is, but I really hope that .Net grows up to enable other way of using it.
You can trim out a lot. Take a look at the techempower benchmarks to see examples of different usage of the framework.
Does it? The frameworks I use today are really, really simple. Polka on Node and Go + a few helper libraries. It's all really simple and clear what's going on, and I can solve problems of just about any complexity I've come across with just those basic tools.
As each of these orthogonal concerns starts drifting in, applications become more and more complex as they 'tack on' support for these in code, rather than having structures in place to allow for extensions and modifications.
Abstractions always have their cost. Complexity exists in the problem domain of the web, and always will. .NET Core is generally well architected in response to a long experience in enterprise and developer concerns. It's not a magical answer to every domain's requirements, but it's generally a damn good compromise ime.
This is a dangerous way to think about complexity management.
And for sure, they are all based on ASP.NET Core. ASP.NET Core is extremely modular which allows, e.g. a middleware stack like Sinatra being built on top of ASP.NET Core's Kestrel webserver (which ... cite once again Techempower benchmarks) beats everything nearby in the current situation. It would be a horrible choice to built a web server framework right now on .NET without using Kestrel. You will never achieve to get close to the performance of that.
Not very likely, but I think separating the two out would help the ecosystem a lot in the long run.
Look at the techempower benchmarks implementation .. they run as close as possible to Kestrel. They have variants with raw kestrel interface, some with low-level middleware (I guess with express like routing) and then full-blown MVC like comfort.
Here is the last techempower for it; https://www.techempower.com/benchmarks/#section=data-r19&hw=...
Also, F# is community owned to my understanding (up to the statement of a MS Research Employee and F# inventor Don Syme to say that the "Microsoft." prefix on ASP.NET Core are not open source community friendly) while C# is 100% design & developed by MS.
Which - IMHO - makes it very delicate for Microsoft to communicate well here.
More F# documentation and support from MS would be great, but IMHO F# examples in the BCL documentation would not be the best use of resources.
1. For a new comer to the language, this is still too much of a hurdle. 2. If I wanted to use F# only as a proxy for C#, then I would rather use C#. I want to write F# code in a functional first and idiomatic way.
This is the stock answer I have gotten in the .Net Community and as someone who wants to use F# for web apps, its a huge turn off. There are pretty much no tutorials, no recent articles and no performant native F# libraries out there. There is no push from MS to improve the situation. and the community is like - This is fine!
Expecting a new user to write c# code with "let" isn't going to fix that.
Giraffe [1] is the de facto standard F# web framework. It's a plugin on top of ASP.NET (for all the reasons described elsewhere - performance, security, ecosystem) that lets you write functional-style 'route >=> function' code without controllers.
If you want a more batteries-included approach, Saturn [2] builds on top of Giraffe to provide, well, more backend batteries (database layer, etc.)
Finally, the SAFE stack [3] are a set of project templates that combine the above with a F# frontend (via the Fable JS compiler) and some Azure deployment helpers.
That said, the new C# language features really do reduce boilerplate when used judiciously - multiple return is now available, "expression-bodied properties", improved template strings etc. Lots of good stuff that is hard to find good documentation for :)
C# 9 also brings top-level programs, which essentially eliminate all ceremony for the entrypoint[0] - an app can now be as simple as:
using System;
Console.WriteLine("Hello World!");
[0] https://dotnetcoretutorials.com/2020/08/30/top-level-program...As far as I've heard it does not exist e.g when it comes for ASP and I believe that what "OP" meant.
I may be very wrong here
For hello world with 29 tokens if i count correctly for C# vs 4 tokens for a Python program, guess where beginners have an easier time to fail?
I used to use LINQPad for that, now I don’t need to, VS Code and this new feature is enough!
You would of course still have all the usual ASP.NET configuration and DI setup to do though, so the impact would be rather limited.
I meant that (as I've heard) you cannot write big app using "top level style" only/mostly
It probably isnt going to reduce "the boiler plate" that people complain about
Having this feature aligns nicely with those use cases.
Its nice for beginners, not having to explain every weird word they see, but not much for professional development.
However managing complexity with various language features all over the project makes impact.
If you write a few programs per day for throw-away data manipulation or system maintenance or something, then no.
>he very sight of dependency injection configuration is cringe.
I'm curious - why?
Regarding Dependency Injection: It's very much suited towards enterprise web applications; and its failure mode is trying to get DI to work seamlessly in a non-web application sense (C# is a general language; and .NET supports console, GUI, and web applications) and once you get out of the we application thread-per-request pipeline, you find yourself hitting rough patches.
First of .NET has excellent documentation, right up there with the PHP. Still my favorite documentation site to snowball through sometimes.
Second, "old DI/enterprisey boilerplate" is what saves you when you get handed the project 5 years down the road, and have to be productive as fast as possible.
Edit:
> So, what’s the best-organized resource for getting up to speed on .NET these days?
Probably just the official documentation: https://docs.microsoft.com/en-us/aspnet/core/?view=aspnetcor...
.NET had excellent documentation. I still pine for the truly-comprehensive MSDN of yore (where "yore" == 2007 or so). Back then, they had less ground to cover (only one .NET Framework and it ran on Windows only), and a bigger budget to do it.
These days, and especially after the big migration to a new CMS a few years back, it's really hit-or-miss for me, especially when it comes to UI framework docs.
Overall though, I have to agree that the .NET docs are very good.
If you want to build apps in an entirely different way that looking nothing like the wretched enterprisey nonsense of the C# and Java worlds, check out SAFE: https://safe-stack.github.io/
As far as starting up F#, I try some of the resources here https://fsharp.org/
However, especially in the HTTP land, the namespace give away instantly on any sample (System.Web => .NET Framework vs. Microsoft.AspNetCore => .NET Core/.NET 5+).
To speed yourself up when you have previous experience: I think the docs.microsoft.com page is not too bad on that.
I should say, as someone who wrote Java/Kotlin for years on IntelliJ, Rider is a welcome addition to the C# world for tooling. JetBrains really does try to produce the best editors they can.
I should mention I use Dart / Flutter, this might not be a problem on Java or Kotlin.
If I don't use the right case it's unable to find the right keyword and most of the time doesn't offer the most relevant option after 'myObject.'
The other day I was joking that my main mode of programming on Visual Studio is pressing CTRL+Space and let the IDE code for me. I can't say the same thing for Android Studio.
> Match case - Select if you want letter case to be taken into account for completion suggestions. Choose whether you want to match case for the first letter or for all letters.
Also, there are a few interesting plugins that improve the autocomplete in IntelliJ further, such as Codota: https://www.codota.com (language support varies)
I don't know what Android Studio uses for Dart, but it's definitely not that! It's definitely not an issue for Java, Kotlin, Go, or even languages with more complex semantics like Rust.
They're noticeably working on making it less terribe lately, but at their current speed and considering the work ahead it's going to take multiple years until they have anything anywhere close to Rider today while JetBrains are developing it at multiple times the speed.
Drawbacks: No XAML hot reloading in WPF, lacks GUIs for Microsoft's questionable file formats (resx). That's it.
Ruby's site even does that visual thing where you can tell it was made only to be seen on Macs.
- runs on x86, x64, arm32, arm64
- runs on Linux
- RedHat adding RedHat specific networking adapters
- runs in Docker
- supports systemd as service manager
- is faster than anything else
- stateless is implementor's choice and easily doable
- Redis, memcached, postgres, mysql, ... driver
- Works on AWS and Azure on Linux OS
- VS Code, Rider (and VS on macOS) and dotnet templates for development
I am not exactly sure what is missing.