News for hackers. Stuff that matters.
Re:.NET 5.0 by mattmanser on Tuesday November 10, 2020 @11:56AM (#25048077)
So, on the plus side with the new .net, I recently made a .net core web app on Linux, and generally it's been pretty easy.

I'm also impressed at just how fast asp.net core is compared to asp.net, the time it takes to open your site in debug mode has dropped dramatically, from what used to be 1/2 minute in asp.net to a few seconds in .net core.

On the bad side? Mainly the asp.net core team and their push for Dependency Injection and the really poor async code has got to be the most frustrating thing about the whole thing.

My biggest bugbear is the way you access your config, which is an absolute and utter kafka-esque mess. Because someone at MS was drinking the DI kool-aid you have to add a minimum of 5 lines of code to any class you want to access config values in, and you're in for an even bigger nightmare if you want to separate business logic and web code into two projects (which is a pretty common design). I've given up with the config DI and just assign them all to static variables. I still don't get why you'd even want your config injected!

The entire authentication uses async code too, which still has all the normal problems of being hard to debug, silently failing if you invoke it wrong and completely overwhelming the callerstack with a bunch of redundant calls.

Huge disadvantages with absolutely zero performance gains for 95% of programmers.

Having been using express again recently, I'm seriously thinking of ditching the asp.net core stack despite my general preference for statically typed languages. C# is great, but the asp.net core are so obsessed with shoving DI and async down your throat and making you write really unpleasant, boilerplate code. Feels like you're back in 1990 with all the FactoryFactoryFactories.

Re:.NET 5.0 by GordonS on Tuesday November 10, 2020 @01:35PM (#25049385)
> My biggest bugbear is the way you access your config, which is an absolute and utter kafka-esque mess. Because someone at MS was drinking the DI kool-aid you have to add a minimum of 5 lines of code to any class you want to access config values in

I'm not sure if maybe you're referring to the Options<T> stuff?

The way I do it is pretty simple.

1. Create a POCO that represents your config. You can have properties for bested configs if you want, e.g. SecurityConfig, MessageBusConfig 2. When the app starts, use a ConfigurationBuilder to build an IConfiguration from whatever Co fig sources you want - typically JSON files and env vars 3. Bind the IConfiguration to your POCO 4. Configure both IConfiguration and the POCO as singletons

Now you can inject the POCO config object wherever you want it, or the IConfiguration should you need it. I feel like this is simple, and works well for dev, test and prod.

Re:.NET 5.0 by Arelius on Tuesday November 10, 2020 @03:49PM (#25051708)
For other people who are curious POCO stands for "Plain Old CLR Object" So I think just a basic uninhereted object.
Re:.NET 5.0 by goric on Tuesday November 10, 2020 @04:39PM (#25052345)
Typically also implies that the object contains no real logic/functionality and is a simple container for storing some values. Something that could be a record type.
Re:.NET 5.0 by JohnL4 on Wednesday November 11, 2020 @08:24AM (#25058137)
I think of "plain old" as meaning "not having dependencies on any framework" as opposed to "not inheriting from anything" or "not having logic".
Re:.NET 5.0 by GordonS on Tuesday November 10, 2020 @05:17PM (#25052797)
Apologies, I usually remember to expand acronyms!
Re:.NET 5.0 by nikolay on Wednesday November 11, 2020 @12:52AM (#25055870)
POCO is the POJO of .Net.
Re:.NET 5.0 by jdking on Tuesday November 10, 2020 @04:17PM (#25052046)
+1 This is the approach I use, to register a config interface in the DI, just grab IConfiguration and bind it to a config class.

The options stuff is a car crash.

Re:.NET 5.0 by starik36 on Tuesday November 10, 2020 @06:24PM (#25053484)
I think the OP is referring to accessing the config 5 layers down from the controller. I've run into it myself. To be able to do that, you have to add Options<T> to the constructor of every class in the chain and then configure DI for it. It just has bad code smell.

On my last project, I just assigned the configs to a static class that's available everywhere and the code was just simply much cleaner.

Re:.NET 5.0 by GordonS on Tuesday November 10, 2020 @06:56PM (#25053778)
> To be able to do that, you have to add Options<T> to the constructor of every class in the chain and then configure DI for it.

You really don't - just inject your populated config object where you need it.

Re:.NET 5.0 by p1necone on Tuesday November 10, 2020 @10:05PM (#25055084)
Why does something 5 layers down need all the config values?
Re:.NET 5.0 by starik36 on Wednesday November 11, 2020 @11:00AM (#25059413)
Not necessarily all options, but just maybe settings for connection to some 3rd party server. You will need the configs.
Re:.NET 5.0 by FroshKiller on Wednesday November 11, 2020 @06:27PM (#25064262)
Why wouldn't you implement a service for the 3rd party that itself requires the config, then? If a caller of the service needs to know how it's configured for some reason, you should probably be exposing it as a property of the service, not sharing the config directly.
Re:.NET 5.0 by reader_mode on Tuesday November 10, 2020 @08:43PM (#25054643)
Smells like you're not doing DI properly :)
Re:.NET 5.0 by scns on Wednesday November 11, 2020 @01:05AM (#25055919)
Is it a bad design, if it could be held wrong?
Re:.NET 5.0 by reader_mode on Wednesday November 11, 2020 @01:09AM (#25055947)
Well from the sound of it he's instantiating objects manually 5 levels deep and he has control over all those constructors since he passed a new parameter through all of them.

So it sounds like basically he's not using DI (is just using it to pass stuff to controllers) and is surprised that using a library designed around DI is awkward. The correct solution is use DI to construct that hierarchy and then you can just request IOptions at the bottom/where you need it.

Re:.NET 5.0 by munchbunny on Wednesday November 11, 2020 @09:31AM (#25058684)
You can hold pretty much anything wrong. Sometimes the onus is on the user to understand the tools. Sometimes the onus is on the tools to not be unnecessarily dangerous. DI is a well understood pattern, it just takes some time to wrap your head around it.
Re:.NET 5.0 by mmargerum on Wednesday November 11, 2020 @07:59AM (#25057943)
“5 layers down”

This is precisely why I jumped ship 5 years ago to Go.

Re:.NET 5.0 by BatteryMountain on Wednesday November 11, 2020 @02:40AM (#25056310)
Code smell OR a pattern, I believe they call it the "Options Pattern". Obviously not a real pattern like other design patterns.
Re:.NET 5.0 by oaiey on Tuesday November 10, 2020 @05:31PM (#25052956)
Exactly. [Removed due to bad wording].
Re:.NET 5.0 by mattmanser on Tuesday November 10, 2020 @06:04PM (#25053285)
Well, work on your reading comprehension, I clearly said I ended up doing exactly that.

Plenty of other people piping up saying they also find this bad abstraction obnoxious, sorry you can't empathise and understand we all have difference preferences.

Re:.NET 5.0 by oaiey on Tuesday November 10, 2020 @06:12PM (#25053353)
My apologies for the wording. Was not intended like that.
Re:.NET 5.0 by 0xcoffee on Tuesday November 10, 2020 @12:14PM (#25048316)
I agree. The first thing I always do is make a custom Settings class which just loads settings via good old `Environment.GetEnvironmentVariable`. Super simple and never failed me.

Bonus Points, by loading all settings at once into strongly typed properties at startup, it will fail fast if a setting is missing, which to me is a benefit.

But I still pass this class via DI to the controllers for testability reasons. If you are using ASP Net, just do things the asp-net way for the sake of other people who have to inherit the code.

Outside of AspNet I never use any automatic DI.

Re:.NET 5.0 by manigandham on Tuesday November 10, 2020 @02:32PM (#25050547)
ASP.NET supports environment variables and uses them by default (that's how the dev/prod environment context is set).

This feature is added in the `config.AddEnvironmentVariables()` line, which is already included in the default host builder. The latest releases use very good conventions and include a lot of the typical functionality. I recommend reading the docs to avoid redoing what's already there: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/co...

Re:.NET 5.0 by nullsense on Tuesday November 10, 2020 @02:22PM (#25050365)
>I agree. The first thing I always do is make a custom Settings class which just loads settings via good old `Environment.GetEnvironmentVariable`. Super simple and never failed me.

The .net core configuration mechanism has a hierarchy of providers it reads from, one of which is environment variables, and strongly typed configuration is supported out of the box, so you're exact use case is supported natively by it.

Re:.NET 5.0 by 0xcoffee on Tuesday November 10, 2020 @03:33PM (#25051514)
I am aware of this, but like many other, I find the IOptions<T> a bad abstraction.

This blog has similar thoughts: https://rimdev.io/strongly-typed-configuration-settings-in-a...

or this blog: https://adamstorr.azurewebsites.net/blog/beyond-basics-aspne...

Or simply google 'asp net strongly typed configuration' and notice everyone seems to be reaching similar conclusions and building their own things.

Just load the setting yourself and register it as a singleton.

Re:.NET 5.0 by davidfowl on Tuesday November 10, 2020 @10:37PM (#25055251)
Options are a very misunderstood abstraction that we have done a poor job explaining. Those blog posts are simplistic and don't explain what you gain and lose by using the options abstraction.
Re:.NET 5.0 by zvrba on Wednesday November 11, 2020 @01:05AM (#25055921)
> that we have done a poor job explaining

Yes, indeed you have. I've tried to both skim and read the "introductory" documentation for `Options<T>` and the only gain I could figure out is monitoring + refresh. I still have no idea how to use it though, so I don't.

Re:.NET 5.0 by macca321 on Tuesday November 10, 2020 @04:04PM (#25051894)
I don't like it either, but one advantage is that the settings can be live updated when the config files change
Re:.NET 5.0 by nullsense on Tuesday November 10, 2020 @10:17PM (#25055135)
The interface just doesn't bother me. I make reasonably good use of the hierarchical config providers including some custom ones. Plus it supports actually being able to live update the config values.

Meh, seems like just an interface to me.

Re:.NET 5.0 by oaiey on Tuesday November 10, 2020 @05:33PM (#25052973)
Do not use Options. Use regular poco bound against Configuration sections like the rest of us :)
Re:.NET 5.0 by SideburnsOfDoom on Tuesday November 10, 2020 @04:33PM (#25052274)
> make a custom Settings class class which just loads settings via good old `Environment.GetEnvironmentVariable

Why would you prefer that, to the the built-in classes to load settings via good old environment variables, among other sources? Which do you think new people coming to your team would prefer to see?

Re:.NET 5.0 by FridgeSeal on Tuesday November 10, 2020 @04:59PM (#25052585)
Because the morass that is HostSetting/HostedServices/etc and friends is a confusing tangle of dependencies (some unspecified) bizarre calls that you've missed and general confusion.

I seriously don't understand how MS managed to make loading some configs so outrageously confusing.

Every time I have to write in .net and I'm forced to go down this path, I've got to go back to the one project where it worked, and copy code across and install dependencies until the whole thing decides it's finally happy.

Re:.NET 5.0 by balabaster on Tuesday November 10, 2020 @12:15PM (#25048329)
You'd want your config injected so that you can swap out configs for test harnesses for continuous integration and deployment. It's one of the mainstays of making your software deployable by automation.
Re:.NET 5.0 by mattmanser on Tuesday November 10, 2020 @12:32PM (#25048525)
You know a better way of doing this?

appsettings.Test.json

Voila, different settings!

I've said elsewhere, the DEFAULT should be super simple, really, really, really easy to use. No thought, no effort, just use it.

If you want to go all crazy and start injecting values into your config in your unit tests, great to have that option, you should have that option. But you're the one who should be scrabbling around writing tons of extra boilerplate code, not me.

But I just want to set a filepath, that's probably never going to change, but might one day. Or an email address to send a weekly summary email to. Or some settings on paging that the client might change their mind about once and I don't want to have to rebuild the project.

The vast majority of config settings are just cover your ass in case you need to one day change this value. They don't need to be tested.

So it not the "normal" path to need to test config values. It's not the path the vast majority of programmers need.

Re:.NET 5.0 by 0xcoffee on Tuesday November 10, 2020 @01:05PM (#25048959)
I'm going to have to disagree here. Having a settings object is much easier then appsettings.Test.json

The .json is for running the application locally. A unit test should be able to cover if a setting has value 'a, b or c', which is much easier with a regular object.

Re:.NET 5.0 by aidenn0 on Tuesday November 10, 2020 @04:00PM (#25051841)
Making software harder to read, write, and maintain in the name of making unit tests easier to read, write, and maintain is putting the cart in front of the horse.
Re:.NET 5.0 by jolux on Tuesday November 10, 2020 @10:33PM (#25055229)
Indeed it would be but making unit tests easier to read, write, and maintain should force you to make the application easier to write and maintain. I agree that readability can suffer somewhat if you’re not careful though.
Re:.NET 5.0 by aidenn0 on Thursday November 12, 2020 @02:29PM (#25073849)
Writing quality tests is often much harder than writing quality software, and I find quality unit tests to be significantly harder than e2e or integration tests, so if I can only write software for which I can also write quality unit tests, I am greatly reducing the space of quality software I can write.

Yes, one solution is to make the software more complicated in order to make the tests less complicated, but the other solution is to just use fewer unit tests. Note that I'm not advocating not testing (my motto with software is "If nobody tested it, then you can be certain it doesn't work."), but One good e2e test can often replace dozens of unit tests.

I find that E2E -> Integration -> Unit form a scale from "easy to write, hard to run" on the e2e side and "easy to run, hard to write" on the unit side.

There are exceptions; testing that you can sort N objects in M microseconds is a trivial test to write, and potentially a challenging requirement to implement, and a unit test might be completely appropriate there. However, for the general case, I find unit tests to be too often trying to make a square-peg fit a round-hole, and then saying "okay we'll shave the corners off a bit so that it's easier to fit in this hole" rather than saying "maybe we should use a square hole"

Re:.NET 5.0 by jolux on Thursday November 12, 2020 @03:28PM (#25074507)
> Writing quality tests is often much harder than writing quality software

I personally believe that tests are how you prove you understand the code you’re writing, and the changes you’re making. If they’re harder to write than the software, you probably need to further clarify the behavior being tested, but they’re going to be hard sometimes, just as some software is hard.

> if I can only write software for which I can also write quality unit tests, I am greatly reducing the space of quality software I can write.

I follow TDD, so indeed I only ever write code that I know how to write unit tests for. I haven’t found that TDD restricts the kind of software that I can write, but sometimes it does mean I’m slower to get started in a particular domain. I do find that once over the initial hump my unit tests are a constant companion that make me more comfortable and productive in developing new software.

Realistically we both agree that testing software is important, we just disagree in the details. The problems I see with end to end testing are that good patterns for building extensible and loosely coupled end to end testing suites are not as widespread in the industry as they are for unit and even integration tests.

My theory as to why is that we assume that end to end tests are going to be slow to run and “heavy” in some sense, and that as such we aren’t running them often enough to force the improvements we need in those suites.

I always find it weird when discussions about unit tests become discussions about other kinds of testing, though. I think high (though not necessarily 100%, as that’s arbitrary) and increasing unit test coverage are an empirical sign of code that is being properly maintained. They are not the last word in testing and software QA, they’re closer to being an indicator like using CI and a proper build system instead of a thousand line shell script, and having quality well-maintained documentation. As I said in another comment, I am not going to say that unit tests are the only way to write good software. They’re a powerful tool that I have found helps me and my teams a lot. That’s as far as I will go.

Re:.NET 5.0 by mattmanser on Wednesday November 11, 2020 @06:15PM (#25064173)
This is simply a dogma, if you want to follow that dogma, fine, but there's no reason to be forcing everyone else to.
Re:.NET 5.0 by jolux on Wednesday November 11, 2020 @09:30PM (#25065764)
I'm not going to force anyone else to, I am expressing an opinion. I would be pushing this position if I were on a team with you because it's not just a dogma, it reflects the best knowledge I have about how to build software well. You are free to build software as you see fit and have always been.
Re:.NET 5.0 by ljm on Wednesday November 11, 2020 @07:11AM (#25057693)
The age old TDD dilemma, that treats the test suite as first class, rather than the end user's experience.
Re:.NET 5.0 by balabaster on Wednesday November 11, 2020 @09:41AM (#25058766)
The end user being the programmer?

I find it humorous that so many programmers still can't see past the end of their nose when it comes to designing code for application testing.

An application is deliverable. That means testable and deployable with a consistent, repeatable process. Anything short of that is not an application, it's a prototype.

Yes, it takes longer to deliver up front, but it removes the long tail of maintenance. Getting a low quality product out of the door makes for a bad user experience and garners you a bad reputation.

The test suite _should_ be a first class citizen.

Re:.NET 5.0 by mattmanser on Wednesday November 11, 2020 @06:36PM (#25064324)
What utter nonsense.
Re:.NET 5.0 by sbelskie on Tuesday November 10, 2020 @12:39PM (#25048611)
I’m confused as to what you want instead of what Asp.Net core offers. Nothing is forcing you to inject configuration or to use IOptions. In most cases you don’t even need to do anything with the configuration builder because that is part of the default of how the host gets setup. You’re configuration should be automatically built from environment vars and appsettings.json.

And of course you can always just access environment variables directly if you want to.

Re:.NET 5.0 by mattmanser on Tuesday November 10, 2020 @01:27PM (#25049264)
I think they should have done what every other framework does and make it super easy to access, like this:

    Env.Config("Settings:MyEasyValue");
Or:

    Env.Config<Settings>().MySuperEasyTypedValue;

And the Dependency Injection? Sure, add some version you can DI with. But not the default.

I now know how to navigate the mess they've made, but it's not time that I feel where I gained anything in my life, it was just frustrating.

Here's one (of many) questions asking simple questions on how to access config values in .Net core:

https://stackoverflow.com/questions/46940710/getting-value-f...

280k views!

And look at the sheer length of that answer.

If you think they succeeded in making a good configuration library, we have very different definitions of success.

Re:.NET 5.0 by maybeOneDay on Tuesday November 10, 2020 @02:13PM (#25050179)
The sheer length of the answer? That's because it shows optional, more advanced ways to get config stuff.

Is this so hard?

    public class AccountController : Controller
    {
        private readonly IConfiguration _config;
    
        public AccountController(IConfiguration config)
        {
            _config = config;
        }
    
        public IActionResult ResetPassword(int userId, string code)
        {
            var vm = new ResetPasswordViewModel
            {
                PasswordRequiredLength = _config.GetValue<int>(
                    "AppIdentitySettings:Password:RequiredLength"),
                RequireUppercase = _config.GetValue<bool>(
                    "AppIdentitySettings:Password:RequireUppercase")
            };
    
            return View(vm);
        }
    }
Re:.NET 5.0 by vonseel on Wednesday November 11, 2020 @06:01AM (#25057349)
Makes perfect sense to me, even as a mostly-Python developer with very limited experience in .NET/C# or other ecosystems.
Re:.NET 5.0 by mattmanser on Wednesday November 11, 2020 @05:08AM (#25057096)
Is this supposed to be ironic? Or just unintentionally?

"What's hard about [mass of code] compared to [one liner]?"

Re:.NET 5.0 by maybeOneDay on Wednesday November 11, 2020 @06:44AM (#25057549)
The "mass" of code is an API controller, not just a way to get settings. It's an example of config use in real code. There are roughly 4 lines of code to get two variables out of the settings.json. This scales quite nicely - if we needed 8 different variables from settings then it would be 10 lines of code for 8 variables.

Sure, it could be done in one line. My point wasn't to say that this is the most terse environmental variable code possible. My point was to say that it's disingenuous to say "look at the sheer length of that answer" as a way to state that the way to get env variables is hugely bloated. It's literally one ctor param and one private variable. If you don't like that for stylistic reasons, that's fine. I understand the argument saying "there should just be a static class with a readonly prop per variable", I just don't think that this particular code is in real terms actually any worse.

Re:.NET 5.0 by nightski on Tuesday November 10, 2020 @01:34PM (#25049371)
It would be pretty trivial to implement the Env class you desire abstracting away the DI stuff.
Re:.NET 5.0 by brynjolf on Wednesday November 11, 2020 @04:10AM (#25056798)
They have that? You can call Configuration manually if you prefer that way. I feel like everyone in this thread is working overtime to justify complaining when there are multiple options to do what you want.
Re:.NET 5.0 by mattmanser on Wednesday November 11, 2020 @05:15AM (#25057130)
I was thinking about this last night, that's actually not at all true.

A 'new' C# programmer doesn't. You have to be advanced enough at C# to know you can do that (i.e. not a junior or outsider)

It's also not clear how the config works at first glance or the implications of using a POCO on the app lifecycle.

An experienced coder will have to ask themselves questions like, if I store the IOptions object, will it automatically update? If I assign the POCO in startup, will it be a single object, or does startup get called for every new request? Or maybe it will get called for every thread? Or maybe if there are no requests for 10 minutes it automatically shuts down?

Re:.NET 5.0 by fearface on Tuesday November 10, 2020 @12:24PM (#25048441)
You can do that just with different config files or env vars too. No need to complicate code for stuff that can be done easily differently as well.
Re:.NET 5.0 by eropple on Tuesday November 10, 2020 @12:28PM (#25048480)
And then you realize that it's 2020 and you don't want configuration files, you want environment variables. Or, now that you've hardstuck yourself on environment variables and built all this stuff around them to set and re-set them properly between tests (now running either in multi-process, which good luck in most environments, or are just running in serial), you're using k8s and the voluming of secrets rather than exposing them as environment variables requires refactoring any code, both operational and testing, that touches them.

"But wait," you say. "I'll just pass in the thing that provides that data"--and you just reinvented DI, albeit likely poorly.

DI is the removal of complication when it is done correctly. (I have no opinion on whether ASP.NET Core does it correctly.)

Re:.NET 5.0 by csharptwdec19 on Tuesday November 10, 2020 @12:39PM (#25048614)
> DI is the removal of complication when it is done correctly. (I have no opinion on whether ASP.NET Core does it correctly.)

I do, it was done in a really weird way and I don't care for the provided DI Abstractions nor the 'Microsoft.Extensions.Configuration' namespace.

To take the 'common' object used for configuration, the nuget package for IOptions<T> requires pulling in Microsoft's DI Abstraction..

That's the first sign of a smell. Config and DI can go hand in hand, but they should still be orthogonal.

The further you go down the DI stack, the more you can see that it's an abstraction has a lot of tradeoffs for front-line devs in the name of using the same abstraction for the underlying framework.

Re:.NET 5.0 by rhencke on Tuesday November 10, 2020 @02:58PM (#25050986)
A better take on DI wireups in .NET: https://nblumhardt.com/2010/01/the-relationship-zoo/

The gist:

    Relationship                                Adapter Type     Meaning
    A needs a B                                 None             Dependency
    A needs a B at some point in the future     Lazy<B>          Delayed instantiation
    A needs to create instances of B            Func<B>          Dynamic instantiation
    A provides parameters of types X and Y to B Func<X,Y,B>      Parameterisation
    A needs all the kinds of B                  IEnumerable<B>   Enumeration
Re:.NET 5.0 by eropple on Tuesday November 10, 2020 @12:43PM (#25048667)
For sure--that sounds real smelly. (Unless it's being used to pull in attributes that are shared between and used for wire-up, but those should then be in a separate assembly.)
Re:.NET 5.0 by to11mtm on Tuesday November 10, 2020 @07:51PM (#25054269)
> (Unless it's being used to pull in attributes that are shared between and used for wire-up, but those should then be in a separate assembly.)

Right. It's primarily interfaces, but they are tangled.

This was especially painful between Net Core 2.0 and 3.1, because moving fast and breaking things is ugly when you have tangled dependencies and everyone is trying to catch up to the breaking API changes and related nuget versioning dance.

Re:.NET 5.0 by mumblemumble on Tuesday November 10, 2020 @01:50PM (#25049600)
> DI is the removal of complication when it is done correctly.

Personally, I would rephrase that as, "DI is a pattern that is designed to mitigate certain kinds of complexity when done correctly."

That leaves room for two ways in which it can backfire. Doing it wrong, like you say, but also doing it in situations where you don't actually have one of the problems it's trying to solve. Cost/benefit ratios always get out of whack when there's no benefit to offset the cost.

Re:.NET 5.0 by eropple on Tuesday November 10, 2020 @03:03PM (#25051063)
That is a fair edit, for sure. Many systems don't need a formal DI mechanism, though should they scale to a certain human-size they'll probably invent enough of one anyway just through composition (if they don't collapse into a ball of mud).
Re:.NET 5.0 by mattmanser on Tuesday November 10, 2020 @12:33PM (#25048539)
You wouldn't be using the config at all if you're not using the config files. They're part of the default project.
Re:.NET 5.0 by ByteJockey on Tuesday November 10, 2020 @10:04PM (#25055081)
How is it that the big enterprise languages haven't gotten the ability to just mock imports yet?

There are certain benefits to DI, but this one seems more like a lack of tooling.

Re:.NET 5.0 by elamje on Tuesday November 10, 2020 @12:05PM (#25048192)
I agree with the DI for config and async push. Too much ceremony for a very simple task. Async being used by auth can certainly be frustrating if you have sync code that needs to use it at some point. Then suddenly you have to redo all sync code that calls the async method.

I’ve been experiencing the same issue with some Azure SDKs that only expose async methods rather than both async and sync. Frustrating to have to redo 8 caller functions to make a single sdk call.

Re:.NET 5.0 by mattmanser on Tuesday November 10, 2020 @02:01PM (#25049901)
You can actually just use `.Wait` or `.Result()` most of the time if you just want to make it synchronous if it's just scrappy code.

Though you'll probably hit the `async void return` runtime bug at some point where you accidentally return void from a method you tried to make async but then got bored of rewriting everything, so just whack in a .Wait or .Result() but haven't returned Task and the damn thing fails at runtime with a mysterious error making you curse async even more.

Re:.NET 5.0 by nullsense on Tuesday November 10, 2020 @02:30PM (#25050494)
>You can actually just use `.Wait` or `.Result()` most of the time if you just want to make it synchronous if it's just scrappy code.

You call .GetAwaiter().GetResult();

and avoid mixing sync and async where at all possible.

Re:.NET 5.0 by ddek on Wednesday November 11, 2020 @04:49AM (#25057006)
Never, ever, ever do this in production. This will block at least two threads, which will cause premature thread pool starvation at spike loads.

This pattern, 'sync-over-async', is to be avoided at all costs, at all times.

You're not going to like it, but the MS recommended way of dealing with this is to make your callstack async.

In all honest - if you're making an ASP net core web app, go all in on async from the start. If you have to mix and match, never go sync-over-async inside an action.

Re:.NET 5.0 by lwansbrough on Tuesday November 10, 2020 @12:07PM (#25048211)
Authentication is in the request pipeline, so it makes sense that it's async if you're talking to some sort of storage engine. We're using the async APIs to pull user/client app information from our database. Why would we want that to be synchronous?
Re:.NET 5.0 by jniedrauer on Tuesday November 10, 2020 @01:52PM (#25049655)
> Why would we want that to be synchronous?

Authentication is blocked by accessing storage. You cannot proceed until the storage read operation is completed. There is no parallel work to be accomplished here. This isn't UI code. There's no event loop. Why would you want this to be asynchronous? This seems like async as a dogma, rather than as a tool to accomplish something specific.

Re:.NET 5.0 by manigandham on Tuesday November 10, 2020 @02:40PM (#25050679)
Async means non-blocking, not parallel. It helps keep the app responsive while using less resources and avoiding lockups and crashes.

.NET is used by millions of developers. Strong and scalable foundations matter, and performance is an explicit goal with asp.net being one of the fastest web frameworks. Async is a core part of this.

There's very little - if any - overhead that you need to worry about with async code from the language to Visual Studio.

Re:.NET 5.0 by merb on Tuesday November 10, 2020 @03:26PM (#25051424)
> It helps keep the app responsive while using less resources and avoiding lockups and crashes.

it actually uses more resources. async has a cost, but it is really low.

Re:.NET 5.0 by asyncawaaait on Tuesday November 10, 2020 @04:39PM (#25052338)
There is a resource tradeoff. async/await has a minor CPU/memory impact, but it can also free up threads to do other work during an I/O bound operation.

Threads have their own resource cost.

Re:.NET 5.0 by nullsense on Tuesday November 10, 2020 @02:33PM (#25050562)
>You cannot proceed until the storage read operation is completed.

Exactly. So when you await it, that thread that would have but blocked waiting for the I/O instead can be used to service other requests until the I/O has finished.

Re:.NET 5.0 by ko27 on Tuesday November 10, 2020 @02:45PM (#25050772)
Async is not used just to enable parallel execution. Using 1 thread per every long running request is a good way to bottleneck your web server.
Re:.NET 5.0 by jen20 on Tuesday November 10, 2020 @03:20PM (#25051327)
> There is no parallel work to be accomplished here.

Concurrency is not parallelism [1].

[1]: https://blog.golang.org/waza-talk

Re:.NET 5.0 by jniedrauer on Tuesday November 10, 2020 @04:17PM (#25052054)
Each HTTP request in a Go webserver spawns a goroutine, and there is no need to think about "freeing up threads" since coroutines are not OS threads. There's also no need to leak the word `async` all over your codebase. The problem being solved here with async/await is also being caused by async/await.
Re:.NET 5.0 by oaiey on Tuesday November 10, 2020 @05:47PM (#25053127)
Goroutine like .NET IAwaitable/Task both abstract the thread away. No one thinks about threads when programming async/await code despite in any await keyword a thread change can happen.

Both solve the same problem with the same technique (under the hood it is all the same). One language had the benefit of late birth (go), the other suffers with its friends through a library/language migration (C#, C++, Java, JavaScript, Python, ...). async/await is effectively the modernization of structural programming to benefit from modern concurrency.

Re:.NET 5.0 by jen20 on Tuesday November 10, 2020 @09:49PM (#25055014)
Worth noting that "late birth" is not the only thing at play here - Rust _had_ green threads at one point and removed them - only to add async/await later.
Re:.NET 5.0 by WorldMaker on Wednesday November 11, 2020 @12:38PM (#25060582)
async/await has underpinnings in monadic computation expressions (via F#/Haskell). There are some benefits to the model, despite a lot of its detractors in the thread here. Such as it is possible to work with multiple monads (many languages that support async/await are not strict about which monad they rewrite for; C# supports any Monad that has a GetAwaiter() method of the right shape, JS supports any object with a then() and/or catch() of the right shape, etc).

While async/await is nowhere structurally as capable/composable as for instance Haskell's do notation, it's still more composable than a lot of alternatives and a lot of manual thread management techniques.

The biggest thing though is that these concerns are orthogonal. You can have green threads backing an async/await monad (with some caveats), but you can't as easily swap in anything that follows monad rules into code written specifically just for green threads. (Python makes you explicitly define your threading model before using async/await; the others provide methods to configure it.)

Which is to say "late birth" isn't really a consideration in async/await, it's as much a consideration of flexibility/composition of abstractions. JS, for example, needed that flexibility/composition in the wild west of multiple disparate Promise implementations early on, and may need it again if/when Browsers ever decide to support proper multi-threading whether it is green threads or something else. In such a future you should still be able to compose existing async/await code without modifying it, even as you take advantage of newer threading options.

Re:.NET 5.0 by jen20 on Tuesday November 10, 2020 @09:52PM (#25055029)
The issue is that Go simply does not allow large classes of system which require direct and unfettered access to the operating system primitives to be built.

I'm a huge fan of Go, but pretending the two systems are equivalent either is either disingenuous or belies misunderstanding.

Re:.NET 5.0 by MarkSweep on Tuesday November 10, 2020 @11:13PM (#25055444)
There is sort of an event loop: the .NET Threadpool. It is used by async by default. It will by default quickly create an number of threads equal to the number of CPU cores, but then slowly increase it beyond that. If you are blocking in a threadpool thread, the work item queue will back up. This is called threadpool starvation.

Some articles:

https://docs.microsoft.com/en-us/archive/blogs/vancem/diagno...

https://github.com/Microsoft/vs-threading/blob/master/doc/th...

Re:.NET 5.0 by asyncawaaait on Tuesday November 10, 2020 @02:22PM (#25050364)
Awaiting a storage operation (ie. look up user) in C# will allow other calls to proceed until the I/O is available to read.

Synchronous code locks you into the model of handling one request per thread.

Given the minor overhead (both cognitive and runtime) of a sync/await, I can’t see why you wouldn’t want to do it here.

Re:.NET 5.0 by balfirevic on Tuesday November 10, 2020 @02:31PM (#25050515)
Because async/await infects everything it touches and forces me to spread irrelevant junk words all over the code which have nothing to do with the task I'm trying to accomplish.
Re:.NET 5.0 by hackerfromthefu on Tuesday November 10, 2020 @08:17PM (#25054451)
What about the far worse stack traces and debugging?

Whats a way to get the utility of normal debugging while using async?

Re:.NET 5.0 by asyncawaaait on Tuesday November 10, 2020 @08:31PM (#25054565)
Stack traces were massively improved in 2.1.

Using a good IDE (Rider or Visual Studio), debugging async/await code works as expected.

Are you doing interop or calling unmanaged code?

Re:.NET 5.0 by hackerfromthefu on Wednesday November 11, 2020 @04:44AM (#25056981)
Thanks, I will make sure to check this out. Does anyone have any articles or documentation on this?
Re:.NET 5.0 by benaadams on Wednesday November 11, 2020 @08:17PM (#25065216)
Stacktrace improvements in .NET Core 2.1: Intelligible stack traces for async, iterators and Dictionary (key not found)

https://www.ageofascent.com/2018/01/26/stack-trace-for-excep...

Re:.NET 5.0 by hackerfromthefu on Tuesday November 17, 2020 @05:59AM (#25122282)
Awesome! Thank you. Wonderful to see these open source contributions to .NET.
Re:.NET 5.0 by mmis1000 on Tuesday November 10, 2020 @12:17PM (#25048351)
For simplicity? Just like how js get async await thing eventually.
Re:.NET 5.0 by buraktamturk on Tuesday November 10, 2020 @12:31PM (#25048515)
async/await is the first class citizen .NET and C#. You just mark your function as async and return Task<OriginalReturnValue> and you can call any async function with await, just like js.
Re:.NET 5.0 by hackerfromthefu on Tuesday November 10, 2020 @08:32PM (#25054568)
That's a factual definition of how to use the first step of async, however it's missing the point.

Async makes your code do significantly more complex thnigs, and while the compiler makes the easy stuff easy, the underlaying complexity hasn't gone away it's just been abstracted, and somewhat leakily.

You can't do 'just' what you said, you also have to deal with of boundary conditions that don't exist in non-async code, plus if you want to understand what your code is doing you now need to keep two mental models of program execution in your mind.

For an introduction to the complexity of async, and practical considerations you need to manage to use it well this official documentation is a place to start - and note the article is pretty long, async does have a lot of additional complexity.

https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/...

Btw I'm not saying don't use Async. Async is an incredibly powerful and valuable tool. But it has costs and those are weighted toward downstream in the software lifecycle and you should be aware of them when deciding which situations that tool is appropriate in.

Yes async is a first class citizen in .NET and thats emphasised by the framework libraries using it everywhere. But they are writing a framework to be consumed widely by users of differing requirements so they have real reasons to support the widest possible use with highest possible performance. Most application code doesn't really have those needs.

Using async should be considered as a tool to reach for (when appropriate) not a default for every situation because it has significant costs through the lifecycle of the system.

Re:.NET 5.0 by ClumsyPilot on Tuesday November 10, 2020 @12:54PM (#25048808)
I fail to see how this is sensible in the slightest - you then have to re-write the code if you want the application to scale. Otherwise you are wasting memory, trashing GC, spawning all these extra threads.All awaitable operations like network requests, disk reads, etc, should be async. Why would you write potato code?
Re:.NET 5.0 by nullsense on Tuesday November 10, 2020 @02:36PM (#25050620)
>Why would you write potato code?

Side note: this gave me a good laugh. I just pictured it being used as a sign off on PR reviews.

Is it a technical term? If it's not I think it should be, and if it is I want to know what the exact nature of potato code is, so I can call it out when I see it in the wild.

Re:.NET 5.0 by Scarbutt on Tuesday November 10, 2020 @09:53PM (#25055036)
you then have to re-write the code if you want the application to scale.

Scaling machines (VMs, containers) is a solved problem and very easy to do today.

Re:.NET 5.0 by withinboredom on Tuesday November 10, 2020 @12:21PM (#25048407)
So you want to pause the thread and keep it from processing other requests for simplicity?
Re:.NET 5.0 by CodesInChaos on Tuesday November 10, 2020 @12:46PM (#25048713)
Unless you have a lot of concurrent connections (C10k problem), having one thread per active request isn't a big deal. For my web applications, requests spend most of their time waiting on the database, and an open transaction is at least as expensive as a thread in an app server for many databases. So I agree that for most applications async isn't worth the complexity they introduce. In many implementations they also mess up your stacktraces, which makes debugging production issues harder.
Re:.NET 5.0 by manigandham on Tuesday November 10, 2020 @02:37PM (#25050643)
.NET has millions of developers. They optimize for the greatest impact and async is necessary for performance. In fact high-performance is an explicit goal of the framework and it ranks at the top of the TechEmpower benchmarks.

Even if you don't need the performance, async code helps keep your app responsive and use less resources on your server. It's far better to have async and not need it then try to refactor your entire ap when it's necessary.

Re:.NET 5.0 by nullsense on Tuesday November 10, 2020 @02:41PM (#25050701)
The web server uses a threadpool anyway. You're not creating threads that don't already exist. You're simply able to use the threads you do have for other tasks while waiting for I/O.
Re:.NET 5.0 by mmis1000 on Tuesday November 10, 2020 @12:34PM (#25048543)
That is literally how php does. Let's fire a thread for every request and block on db reading or any action that require io. And it seems it works (at least for php)
Re:.NET 5.0 by virgilp on Tuesday November 10, 2020 @12:49PM (#25048750)
.NET is meant for stuff like microservices; you don't see lots of those written in php, right?

Also, for high-traffic websites, that's really not a great idea. You might say "but Facebook, PHP" - I'm really certain that their current codebase doesn't have a thread that blocks on DB for each user request.

Re:.NET 5.0 by zerkten on Tuesday November 10, 2020 @02:18PM (#25050294)
> .NET is meant for stuff like microservices;

What does this mean? .NET has been around before SOA was a term and microservices is an evolution of that. The concepts are orthogonal and you could write microservices in PHP, if you really wanted. Like Java, the .NET runtime and platform is highly efficient. That's what .NET has historically had over PHP/Python/Ruby, but I don't keep up with the PHP and Ruby platforms these days.

I feel like this is another one of those discussions like the "Python GIL problem." Whether it's a really a problem depends on the circumstances, and the circumstances were it is a problem affects fewer people than the HN threads suggest.

Re:.NET 5.0 by int_19h on Tuesday November 10, 2020 @03:33PM (#25051520)
I'm not sure where SOA as a specific term showed up, but the very first release of .NET very much emphasized web services in the docs, presentations etc. Back then, this meant SOAP.
Re:.NET 5.0 by BoorishBears on Tuesday November 10, 2020 @01:26PM (#25049250)
I don't get why the auth being async is a hang up but at the same time, most projects can handle not scaling to Facebook-scale and the sooner developers accept that, the sooner we can escape a great gnashing of teeth.

I'd be willing to bet more projects have been killed by trying to architecture for performance up front than have been killed by being too successful for their own good and keeling over.

If Twitter could make it past the Fail Whale days, I think most of us can too.

Re:.NET 5.0 by virgilp on Tuesday November 10, 2020 @02:12PM (#25050158)
I'd agree if you talk about "most projects". But here we're talking about a platform - you can't fault Microsoft for caring about performance! .NET is absolutely not meant only for small sites, my current employer is heavily invested in .NET and we'd probably be dead (performance-wise) without async. Definitely couldn't run our services with PHP (not without Facebook-like investments), we already outgrew that kind of traffic.
Re:.NET 5.0 by oaiey on Tuesday November 10, 2020 @05:51PM (#25053158)
Until you look who is faster and has more througput. The only way how PHP can do (via swoole and friends) is by adopting non-blocking frameworks. And remember througput * duration = Serverlese costs
Re:.NET 5.0 by jhomedall on Tuesday November 10, 2020 @12:58PM (#25048864)
That's just standard threading, not async/await.
Re:.NET 5.0 by mdpm on Tuesday November 10, 2020 @04:33PM (#25052273)
The async stuff may require some attention, but it's part of the performance story when dealing with many requests, not when evaluating just one.

As regards configuration, all the means you could want for configuration are there. You can access items directly [1], or via strongly typed objects. These all support multiple sources of configuration data, and many means of overriding them.

I generally really don't like environment variables as they expose configured secrets to everything in the same machine / container, but we make use of the standard configuration system's environment variable overrides, but we use akv2k8s.io and thus only expose secrets to the container's entry point application.

[1] public Startup(IConfiguration config) { // injects config store var setting = config["yourConfigKey"] // ... but you now have to convert this from a string for any other datatype }

Re:.NET 5.0 by jiggawatts on Tuesday November 10, 2020 @03:19PM (#25051302)
> [Async has] Huge disadvantages with absolutely zero performance gains for 95% of programmers.

One curious thing is that Java has elected to use lightweight threads instead of async methods: https://www.javacodegeeks.com/2019/12/project-loom.html

Their arguments are compelling:

- Works with existing debuggers and debugging techniques.

- Stack traces aren't polluted with irrelevant garbage.

- Doesn't create method apartheid, where async and non-async can't "mix".

- Doesn't force library authors to "buy into" the async model.

Re:.NET 5.0 by int_19h on Tuesday November 10, 2020 @03:27PM (#25051440)
- Cannot interop with other languages/VMs that do async differently.

The nice thing about promise-based async is that it's very easy to map to straight C ABI callbacks, which means that it can be fully cross-language. Green threads are runtime-specific.

Re:.NET 5.0 by Ironlink on Tuesday November 10, 2020 @03:38PM (#25051585)
"Cannot" seems a bit harsh. CompletableFuture isn't going away, and is made for callback situations.

With green threads being "free" (you can have millions), it might be reasonable to just block your green thread until the callback arrives.

Re:.NET 5.0 by jackfoxy on Tuesday November 10, 2020 @04:16PM (#25052035)
Completely do away with dependency injection by using one of the many available F# options, for instance SAFE stack.

Should be able to likewise give you a much simpler and understandable config model.

https://safe-stack.github.io/

Re:.NET 5.0 by GordonS on Tuesday November 10, 2020 @01:45PM (#25049500)
> and you're in for an even bigger nightmare if you want to separate business logic and web code into two projects (which is a pretty common design)

I do this with a lot (most?) web apps, and don't have any issues with it at all - what kind of problems are you seeing?

Re:.NET 5.0 by asdfman123 on Tuesday November 10, 2020 @03:31PM (#25051495)
Yeah, the DI stuff is a lot, but eventually bringing in the dependencies becomes total autopilot.

> I've given up with the config DI and just assign them all to static variables.

Not to be a fanboy, but it's designed in a way where you CAN use all the fancy features. If you want something simpler, you can just do exactly what you did.

This syntax is probably wrong because I'm doing this from memory, you should probably also use the Lazy class or something, and if I were to actually write this code I'd think twice about thread safety -- but if you want simple static access to config values, you can just do this:

public static MyConfigPoco MyConfig {get;set;} = JsonConvert.DeserializeObject<MyConfigPoco>(File.ReadAllLines("appsettings.json")) ;

Re:.NET 5.0 by nicoburns on Tuesday November 10, 2020 @12:35PM (#25048566)
Can't you just ignore the built in configuration and roll your own (probably there's a dotenv library?). That said, I've also personally moved away from C# despite really likeing the lanaguage due to a lacking ecosystem.

I'd recommend both node with TypeScript and Rust for backend web development in a statically typed langauge.

Re:.NET 5.0 by StreamBright on Tuesday November 10, 2020 @01:17PM (#25049137)
We started to use F# with Elm and it works very well. Statically typed all the way.
Re:.NET 5.0 by angio on Tuesday November 10, 2020 @03:31PM (#25051487)
This year I converted a standard F#+Giraffe backend and React+Typescript frontend to use Feliz [0] with Fable.Remoting [1] and it has been a pleasant experience.

[0] https://github.com/Zaid-Ajaj/Feliz

[1] https://github.com/Zaid-Ajaj/Fable.Remoting

Re:.NET 5.0 by francisl on Tuesday November 10, 2020 @05:38PM (#25053025)
why not go all the way with fable + elmish for the Frontend?
Re:.NET 5.0 by angio on Wednesday November 11, 2020 @06:35AM (#25057499)
Good question, in my experience using Feliz is easier to integrate with existing react components. For state management I use `UseElmish` [0] so I get an experience that's pretty close to pure Fable + elmish.

[0] https://zaid-ajaj.github.io/Feliz/#/Hooks/UseElmish

Re:.NET 5.0 by apalmer on Tuesday November 10, 2020 @06:28PM (#25053518)
C# lacks and ecosystem... I understand that.

But C# lacks an ecosystem compared to Rust? I don't understand that.

Re:.NET 5.0 by ceesharp on Tuesday November 10, 2020 @01:03PM (#25048940)
Which libraries did you miss from the ecosystem?
Re:.NET 5.0 by davidspiess on Tuesday November 10, 2020 @12:48PM (#25048728)
Is Rust mature enough for web development already?
Re:.NET 5.0 by nuggien on Tuesday November 10, 2020 @01:01PM (#25048910)
Re:.NET 5.0 by davidspiess on Tuesday November 10, 2020 @01:11PM (#25049043)
The last time i looked into it, all the big cloud providers lacked officially supported Rust SDKs.
Re:.NET 5.0 by nicoburns on Tuesday November 10, 2020 @01:54PM (#25049697)
Rusoto for AWS is unofficial but excellent (and auto-generated off of the official botocore API definitions).
Re:.NET 5.0 by Lendal on Tuesday November 10, 2020 @12:05PM (#25048183)
I found Go to be a really nice replacement for C#. It has the static typing and garbage collection, but you also get a self-contained binary executing without the requirement of an external runtime environment. I also discovered that I don't miss classes at all.
Re:.NET 5.0 by tester756 on Tuesday November 10, 2020 @12:09PM (#25048241)
>but you also get a self-contained binary executing without the requirement of an external runtime environment.

I'm not sure whether we're talking about the same thing, but you can publish Self-Contained App (basically your app and framework together) and you don't have to install anything.

Re:.NET 5.0 by svnpenn on Tuesday November 10, 2020 @01:17PM (#25049129)
This is technically true, but it's a difference of a 5 MB executable vs a 50 MB.
Re:.NET 5.0 by littlecranky67 on Tuesday November 10, 2020 @02:56PM (#25050938)
Is it, actually? I mean, yes of course its 45MB difference, but does this matter? We are not talking about applications downloaded to a browser (webapp) or to a mobile phone. In a time where I download >50GB+ games on Steam and deploy from CI/CD server or docker registries to my servers, is a size of 50MB or 100MB really a showstopper?

Don't get me wrong, I totally love 4k and 64k demos and am always fascinated what could be packed into such small binaries, but in my professional life I think developer productivity, code quality and tooling is way more important than filesize. This is of course different if you are a webdev that ships .js, or an App developer publishing to Appstores.

Re:.NET 5.0 by tyrrrz on Tuesday November 10, 2020 @04:39PM (#25052344)
The only environments where self-contained deployment matters are the ones you mentioned: browser, mobile phone, and also desktop. So yes, 45mb is a big difference (actually my app is 250mb).
Re:.NET 5.0 by ablekh on Tuesday November 10, 2020 @06:18PM (#25053416)
In the .NET context, browser-targeted deployments can have a minimal download overhead of around 2 MB, which is a far cry from 50 MB. How? Blazor. For details, see https://blog.ndepend.com/blazor-internals-you-need-to-know.
Re:.NET 5.0 by cutler on Tuesday November 10, 2020 @09:26PM (#25054887)
That's 2Mb front-end which is quite heavy.
Re:.NET 5.0 by ablekh on Tuesday November 10, 2020 @10:23PM (#25055172)
How 2 MB could be considered heavy, when visiting most websites results in much larger sizes of downloaded resources?
Re:.NET 5.0 by littlecranky67 on Wednesday November 11, 2020 @04:30AM (#25056902)
tell that to websites auto-playing videos (in muted state) or even better, using videos as page background that play without interop.
Re:.NET 5.0 by Richicoder on Tuesday November 10, 2020 @09:53PM (#25055033)
.NET has trimming now, so it is 5 MB? (Possibly less!)
Re:.NET 5.0 by svnpenn on Saturday November 14, 2020 @04:24PM (#25095759)
Nope.

Running this command:

    dotnet publish `
    -p:Configuration=Release `
    -p:PublishSingleFile=true `
    -p:PublishTrimmed=true `
    -p:RuntimeIdentifier=win-x64
gives an 11 MB file, that still requires 4 DLL as well.
Re:.NET 5.0 by Xeronate on Tuesday November 10, 2020 @04:57PM (#25052545)
Go seems nice, but don’t you think writing business logic feels very tedious compared to C#? Generics and linq speed development time up for me significantly.
Re:.NET 5.0 by cutler on Tuesday November 10, 2020 @09:31PM (#25054917)
I can't think of anything other than Java that's as tedious to write as C#/ASP.Net. With Java and C# code you spend a siginifcant amount of your time messing with the complexities of the language itself instead of dealing with your business problem. The mixture of generics and static typing is particularly pernicious. I really hope Go 2.0 doesn't end-up going down the generics rabbit hole.
Re:.NET 5.0 by Xeronate on Wednesday November 11, 2020 @02:12AM (#25056181)
Can you give some concrete examples of how C# is tedious compared to go?

Things like

  var filtered = purchases.Where(x => x.Name.Contains("Sean"));
and

  var grouped = purchases.GroupBy(x => x.Buyer).Where(x => x.ToList().Count > 10).ToDictionary(x => x.Buyer, x => x.ToList());
etc. come up a lot in day to day programming and always feel tedious to me in go. The first example in go looks something like

    filtered := []purchase{}
    for i := range purchases {
        if purchases[i].buyer == "Sean" {
            filtered = append(filtered, purchases[i])
        }
    }
and it only gets worse as the domain gets more complicated. I don't really know what your background is where you feel that static typing and generics are complicated. I write C# every day and spend 0% of my time fighting the language.
Re:.NET 5.0 by 0x445442 on Wednesday November 11, 2020 @10:05AM (#25058944)
Same experience here for Java. I always have a hard time understanding the arguments against it. The platform and tooling far exceed that of Go and I've never found the writing of actual code to be anywhere near the bottle neck in the entire development process. And while I've never worked professionally with C#/.NET, I imagine it's a very similar experience.
Re:.NET 5.0 by bschwindHN on Wednesday November 11, 2020 @02:00AM (#25056138)
I have to agree with Xeronate on this one, a lack of generics makes writing business logic in Go quite annoying. Generics and the monad-esque values it enables make it much easier to model your logic properly.

I like Go for services that just need to push bytes around to various places but otherwise it does get quite tedious for complex logic.

Re:.NET 5.0 by Xeronate on Wednesday November 11, 2020 @02:16AM (#25056198)
What types of services don't have complex business logic? Just trying to expand my horizons. I guess like a video transcoding service or something like maybe.
Re:.NET 5.0 by bschwindHN on Wednesday November 11, 2020 @02:47AM (#25056342)
Something like a WebSocket server, a load balancer, message queue, that sort of thing.

It's not that those aren't also complex, but there's less "business" in the logic, if that makes sense. Something that doesn't handle arbitrary user input or deal with the messiness of humans, like first/last names, dates and timezones, etc.

As an example, I had once written a WebSocket server in go which took a program as input, ran it in a heavily stripped down docker container, and streamed the stdout back to the client. Go was perfect for that use case. (though to be honest I'd pick Rust now because I'm past the learning curve on it)

Re:.NET 5.0 by lwansbrough on Tuesday November 10, 2020 @12:10PM (#25048251)
You don't need the .NET runtime installed on the target host.
Re:.NET 5.0 by leguy on Tuesday November 10, 2020 @04:00PM (#25051843)
C# doesn't require classes with the latest release.

In what capacity are you using Go that made it a good replacement for C#? Microservices? If so, which framework are you using?

Re:.NET 5.0 by js4ever on Tuesday November 10, 2020 @01:07PM (#25048992)
I have migrated from C# to Node.js, my code is now 20x times shorter (from 800 files to 40 files), simpler to read and maintain, there is 100x more packages available on NPM compared to nuget. Performance is stellar, even better than in C# for my use case (Mega tons of concurrent queries executed in 1-5ms avg)

And also I don't have to fight against the language to do what I want to do ... No classes, no types, no constraints.

Re:.NET 5.0 by littlecranky67 on Tuesday November 10, 2020 @02:57PM (#25050962)
Every rewrite yields better results, even if you'd have rewritten your code in (modern) C# again.
Re:.NET 5.0 by Xevi on Tuesday November 10, 2020 @05:37PM (#25053017)
> my code is now 20x times shorter (from 800 files to 40 files)

Well, do you have all of the bells an whistles that you had with .NET? I mean, you can shrink a .NET API down to pretty much just 1 file if you really want to. The question is if you should.

WebHost.CreateDefaultBuilder().Configure(app => app.Run(c => c.Response.WriteAsync("Hello world!"))).Build().Run();

Re:.NET 5.0 by tester756 on Tuesday November 10, 2020 @01:18PM (#25049146)
>20x times shorter

that's giant, but I don't think that "just" language / environment difference makes this huge difference

Re:.NET 5.0 by Scarbutt on Tuesday November 10, 2020 @01:30PM (#25049314)
I would say 2x-5x shorter is pretty realistic.
Re:.NET 5.0 by balfirevic on Tuesday November 10, 2020 @02:23PM (#25050398)
I would say that that C# code that can get 2x-5x reduction in size by being rewritten in JS is terribly bloated (not taking into account the case where you just remove code because there is now a library available for what you had to do yourself before).
Re:.NET 5.0 by merb on Tuesday November 10, 2020 @03:29PM (#25051467)
yeah javascript is pretty short. unfortunatly I do not know how people love it. npm/yarn and javascript dependency management is the worst thing i've ever seen and it is slow and pulls in millions of files, just for a small project.
Re:.NET 5.0 by ArtifTh on Tuesday November 10, 2020 @01:41PM (#25049458)
Huh, that's quite a dramatic code size reduction. Which percentage of this codebase was in tests and boilerplate code for stuff like helper data classes?
Re:.NET 5.0 by kumarvvr on Tuesday November 10, 2020 @10:36PM (#25055242)
Also, I find DI to be very useful. I dont know about small projects, but in any reasonable size projects, having a DI container is a god send. Easy to setup and use.
Re:.NET 5.0 by Netcob on Wednesday November 11, 2020 @04:16AM (#25056833)
Yeah, I'm pretty shocked how much hate it seems to get. Maybe it just makes things easier for simpletons like me?

The one issue I can see with DI in ASP.NET Core is that it doesn't really do DI correctly. The point of DI is that ultimately, you have complete control over how you build your dependency graph and you shouldn't be forced to use a container at all if you don't want to. With a DI abstraction the developers are basically saying "you can do what you want, as long as it's pretty much exactly what we expect you to do".

This explains this pretty well: https://blog.simpleinjector.org/2016/06/whats-wrong-with-the...

Re:.NET 5.0 by mycall on Friday November 13, 2020 @12:41AM (#25079280)
That is 4 years old, is it still relevant?
Re:.NET 5.0 by Netcob on Sunday November 15, 2020 @08:02PM (#25106747)
Yeah, that whole approach hasn't really changed at all. I'm not sure how MS could even realistically change it without breaking a lot of stuff, so I think it's more of an example of what to avoid.
Re:.NET 5.0 by tester756 on Tuesday November 10, 2020 @12:08PM (#25048221)
>and you're in for an even bigger nightmare if you want to separate business logic and web code into two projects (which is a pretty common design). I've given up with the config DI and just assign them all to static variables.

So you have static variable in web project and then add reference to web project to obtain that config? Do I get that right?

I never felt like config DI was a problem once you did all the stuff that you do at the beginning of the project

Re:.NET 5.0 by mattmanser on Tuesday November 10, 2020 @12:14PM (#25048306)
To me it's just so pointless, here's an example:

    using Microsoft.Extensions.Configuration;  //extra line
    using Microsoft.Extensions.Options;    //extra line

    public class AdminController : Controller
    {
        IOptions<Settings> settings; //extra line

        public AdminController(IOptions<Settings> settings) //extra code
        {
            this.settings = settings; //extra line
        }
        

        public void RandomMethod()
        {
            var a  = settings.Value.FinallyMySetting; // 5 extra lines to access your config, genius...
        }
    }
A complete and utter waste of my time to put all those lines in, it's just pointless boilerplate trash, which C# has been getting rid of excellently, all to be undone by whoever wrote Microsoft.Extensions.Configuration. And you have to do it any where you want to get a config value.

On top of that, if you want to use it in a console app, you have to add like 5 packages. Yes, FIVE.

    <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.9" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="3.1.9" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.9" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.1.9" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.9" />

Then add this delightful mess just to initialize it:

    var environmentName = Environment.GetEnvironmentVariable("ENVIRONMENT");

    var builder = new ConfigurationBuilder()
                .AddJsonFile($"appsettings.json", true, true)
                .AddJsonFile($"appsettings.{environmentName}.json", true, true)
                .AddEnvironmentVariables();
 
    var configuration = builder.Build();
When you compare that to what any other framework does, it just beggars belief that they though this was a good way of handling config.

When I was setting this all up, I obviously hit up SO, and it's clear from many of the (incorrect) answers on SO that people just don't get it. It's too complicated for something that should be super simple.

I get that it's handy to be able to configure all that yourself, but all of that should be default and a single line/package.

Re:.NET 5.0 by smcl on Tuesday November 10, 2020 @01:09PM (#25049010)
I agree that there's a bit of boilerplate, but in this case it's boilerplate that's normally already handled when you're using GenericHost or WebHost builders - which will setup all this Configuration, Logging and Dependency Injection for you (take a look here for an example https://dfederm.com/building-a-console-app-with-.net-generic...). I don't know what kind of console apps you're writing, but if they require DI and environment-specific configuration files then you'd likely be better off using GenericHost. Setting all this up by hand is a bit cumbersome, but I don't think they were really intended to be used that way.
Re:.NET 5.0 by fabian2k on Tuesday November 10, 2020 @12:50PM (#25048756)
Apart from needing two namespaces, this does look reasonable to me. I'm not sure how you could make constructor-based dependency injection easier without making it less obvious what is happening. And most of the additional lines are stuff your editor can do for you, even in VS Code you can automatically generate the field and assignment and the imports after just typing the constructor parameter.

ASP.NET Core does push you strongly towards dependency injection, but it does not force you at all to use it.

Re:.NET 5.0 by FridgeSeal on Tuesday November 10, 2020 @05:14PM (#25052764)
> ASP.NET Core does push you strongly towards dependency injection, but it does not force you at all to use it.

Their own documentation for making queries against SQL Server doesn't provide examples of how to do it that aren't using DI. "Just inject it" it just says. Thanks .net, super helpful. Maybe the docs are there, but I couldn't find them at all when I went looking.

Re:.NET 5.0 by mattmanser on Tuesday November 10, 2020 @07:35PM (#25054131)

    using(var conn = new SqlConnection("<conn-string>"))
    using(var cmd = new SqlCommand(@"Query here", conn))
    {
      conn.Open();
      cmd.executeNonQuery();
    }
Re:.NET 5.0 by FridgeSeal on Wednesday November 11, 2020 @12:26AM (#25055735)
Hmmmm, maybe I am just dense hahaha.
Re:.NET 5.0 by vp8989 on Tuesday November 10, 2020 @01:17PM (#25049141)
In their defence, there is a default builder that would save you maybe 3-4 lines there, but I do generally agree with your point.

It is something that annoys me about .NET in general there is just decades of over-engineering cruft and once these practices emerge its difficult to get people to stop doing them. The problem only gets worse as time passes.

Re:.NET 5.0 by LandR on Tuesday November 10, 2020 @04:17PM (#25052053)
THe last time I used .net core and had to handle some config was a nightmare like you describe. The documentation wasn't great either. The whole way everything is complicated and messy made me want to just quit my job.

It's such convoluted nonsense.

I like C# but sometimes it feels like MS main aim is to make developers miserable.

Re:.NET 5.0 by SideburnsOfDoom on Wednesday November 11, 2020 @03:32AM (#25056578)
> it's just pointless boilerplate trash,

I don't regard the "ConfigurationBuilder" and following lines as "boilerplate" exactly, since by not using the default HostBuilder and instead including that code, you are making choices.

Specifically, you are choosing to pull in settings from "appsettings.json", "appsettings.{env}.json" and then environment vars, in that order, and specifying that both files are optional and should reload on change.

You can make other choices, with other code.The code is there to "configure the config", i.e. to make those choices.

Re:.NET 5.0 by fuzzy2 on Tuesday November 10, 2020 @01:09PM (#25049018)
I'm mainly interested in one statement:

> it's just pointless boilerplate trash, which C# has been getting rid of excellently

Could you elaborate on how you feel C# avoided this?

From my point of view the only alternative (to DI with constructor injection) is static members somewhere, which does not scale. Maybe property injection, but ugh.

Re:.NET 5.0 by didibus on Tuesday November 10, 2020 @02:09PM (#25050093)
I think they want to use something more like an environment contextual config fetcher instead.

For example:

test.appsettings.json

{"db-url":"test.url.here"}

prod.appsettings.json

{"db-url":"prod.url.here"}

Now in the code:

Settings.fetch("db-url");

// Will return the test one if environment variable says we are running under test environment, else will return the prod one.

Re:.NET 5.0 by WorldMaker on Wednesday November 11, 2020 @12:57PM (#25060827)
The DI-based configuration system can be configured to do exactly that. Though yes, the configuration is maybe harder than it should be simply because it isn't on by default.

A lot of the complexity in the configuration system exists to enable a lot of configuration options. I have some ASP.NET applications that get some configuration from Environment Variables on the host machine, some from environment-specific config files, some from a configuration service (specifically Azure Key Vault), all without any of my DI-injected downstream components specifically needing to know which source provided specifically which configuration key. For the DI injected things it is just `config["db-url"]` or maybe type-safe class if I DI-inject an IOptions<T> (or add my type-safe classes directly to the DI without the IOptions<T> wrapper, which is another configurable option).

It's absolutely a very complex system, but with great complexity comes great flexibility (to badly paraphrase the Spider-Man mantra).

Re:.NET 5.0 by nightski on Tuesday November 10, 2020 @12:28PM (#25048481)
Do you type every line typically? If you use Rider or VS pretty much every one of those lines can be auto generated with autocomplete. Also, this can easily be worked around. Just create a Singleton which has the settings injected into it. I prefer the testability of the injected version but if you'd rather access a static global it is very easy to do.
Re:.NET 5.0 by tester756 on Tuesday November 10, 2020 @12:39PM (#25048605)
I do agree

I just type IOptions<T> config in ctor, use ctrl+. and private readonly property and it's initialization is generated

Re:.NET 5.0 by mattmanser on Tuesday November 10, 2020 @12:44PM (#25048676)
That doesn't work unless you already have the using statements, which you won't have as you haven't added it yet.

I just tried it.

Re:.NET 5.0 by tester756 on Tuesday November 10, 2020 @12:57PM (#25048847)
I'm using Roslynator:

https://i.imgur.com/cWs1M77.png

and I have some naming rule

https://i.imgur.com/iPwNj5b.png

So I basically have to type IOptions<T> Name and use ctrl+. twice in order to generate private readonly property and initialize it and add using to IOptions

Re:.NET 5.0 by merb on Tuesday November 10, 2020 @01:44PM (#25049484)
you can use property injection when you use something like autofac as the di container.
Re:.NET 5.0 by FridgeSeal on Tuesday November 10, 2020 @05:19PM (#25052822)
Cool, so I'll add another dependency and figure out how to use that, to save myself time having to write out MS's convoluted dependency-injected configuration code.
Re:.NET 5.0 by nightski on Saturday November 14, 2020 @08:40PM (#25097368)
Meanwhile one could of have this solved in their projects in less than the time it took to have this HN discussion and moved on with their life. Seriously, somethings are worth complaining over, others are not.
Re:.NET 5.0 by merb on Tuesday November 10, 2020 @06:45PM (#25053660)
well you don't need to use dependency injection at all. there. is no need to use IConfiguration.

also as far as I heard, is that microsoft is working on a micro web framework, that does not use di. (something like https://github.com/featherhttp/framework, just more official i guess)

Re:.NET 5.0 by cutler on Tuesday November 10, 2020 @09:50PM (#25055020)
Talk about Stockholm Syndrome. Classic enterprise public SomethingBuilder builder = new SomethingBuilder() ; builder.AddFanfoldConfig() ; builder.build(). Sun, Microsoft and Oracle and have hoodwinked generations into believing this kind of crap is the Rolls Royce of software development and we let them get away with it.
Re:.NET 5.0 by davidfowl on Tuesday November 10, 2020 @10:45PM (#25055305)
> When you compare that to what any other framework does

Can you show me what that looks like?

Re:.NET 5.0 by ceesharp on Tuesday November 10, 2020 @01:17PM (#25049131)
You don't need to inject IOptions, you can inject the Settings class directly. I don't see an issue with those extra lines, VS generates them with one hotkey for me.
Re:.NET 5.0 by BatteryMountain on Wednesday November 11, 2020 @03:07AM (#25056438)
You also have to understand that shoving async down our throats is part of the philosophy of how aspnet core and kestrel (built ontop of libuv) is implemented: the whole stack is built to run async and with DI in mind. aspnet core itself uses the same DI system to manage itself.

No part of aspnet core is built to run synchronous. Its all async all the way down.

Re:.NET 5.0 by nexus2045 on Thursday November 12, 2020 @03:48PM (#25074773)
This is a pretty interesting comment section to read. I went from Node.js to .NET Core development for about a year, and got the impression that Microsoft had already figured out all the best practices, and shoving it down my throat was for my own good, so I didn’t question whether or not DI was good, as if it was dogmatic. My team thinks the same. I thought DI was pretty much the final conclusion to how software should be architected due to the collective trial-and-error of decades of OOP programmers.

In usual HN fashion, even the most seemingly obviously true points to me are being argued and refuted.

Re:.NET 5.0 by cm2187 on Tuesday November 10, 2020 @12:18PM (#25048373)
Agree with your complaint on async. And on asp.net, async doesn't disrupt that much the workflow (but creates the possibility for deadlocks). But if you are dealing with a UI and make a method async, then suddenly you have a ton more problems to deal with, like what happen if the user changes the state while you are waiting for an async call. That increases a lot the complexity of the code. Which is why I am lukewarm about their approach of mandating async for new features.
Re:.NET 5.0 by asyncawaaait on Tuesday November 10, 2020 @02:27PM (#25050452)
How does async/await introduce complexity where threading wouldn’t?

In my experience, the complexity is vastly reduced by not having to implement tricky asynchronous APIs (Task Paralell, thread pools, BackgroundWorker, etc).

Re:.NET 5.0 by cm2187 on Tuesday November 10, 2020 @02:50PM (#25050839)
no, vs blocking the UI thread. Which is perfectly fine the vast majority of the cases, unless you are running something long running.
Re:.NET 5.0 by huzaif on Tuesday November 10, 2020 @03:33PM (#25051518)
You are trying to something slightly complex. I don't see how one could make it any easier from a language design perspective and staying idiomatic to the language.

Go: Goroutines make you wire the "stop" scenario on your own (channel close). Rust: Hold on to your future and drop() it. C#: Pass a cancellation token and call Cancel()

All seem reasonable and stay within what they think their developers will be able to pick up and run with.

Re:.NET 5.0 by spaetzleesser on Tuesday November 10, 2020 @01:57PM (#25049813)
Agreed. Async is nice on the server but on the desktop it’s a real problem. For a while they had both sync and async but now it’s often only async.

I just finished an app that had to shutdown while some async operations were still not finished. Really hard to manage compared to using threads.

Re:.NET 5.0 by lukevp on Tuesday November 10, 2020 @02:37PM (#25050638)
How is Task.WaitAll different from Thread.Joining a bunch of threads? Or if you were cancelling tasks, using cancellation tokens?
Re:.NET 5.0 by hansvm on Tuesday November 10, 2020 @03:25PM (#25051402)
The other comment alluded to this, but the crux of the problem is that you can schedule a task to run and wait on the completion of that task, but the only available thread for it to run is the one currently waiting for it to complete. The writeup here isn't bad: https://devblogs.microsoft.com/pfxteam/await-and-ui-and-dead...
Re:.NET 5.0 by cm2187 on Tuesday November 10, 2020 @02:50PM (#25050854)
If you are running Task.WaitAll on a UI thread you are likely to create a deadlock.
Re:.NET 5.0 by zmj on Tuesday November 10, 2020 @05:35PM (#25052990)
The move to async trades one set of problems for another. Yes, implementing cooperative cancellation is tricky. On the other hand, recovering from corrupted state caused by Thread.Abort is also tricky.
Re:.NET 5.0 by userbinator on Tuesday November 10, 2020 @08:24PM (#25054516)
C# is great, but the asp.net core are so obsessed with shoving DI and async down your throat and making you write really unpleasant, boilerplate code. Feels like you're back in 1990 with all the FactoryFactoryFactories.

It's been said that C# is "Microsoft's Java". That applies not only to the language, but the culture of "enterprise-ism" (insanely excessive abstraction and complexity) that seems to permeate throughout the code.

I worked briefly with Enterprise Java a long time ago, and it brings back much of those memories whenever I have to look for something in a C# codebase.

Re:.NET 5.0 by reader_mode on Tuesday November 10, 2020 @08:55PM (#25054725)
C# tilts in that direction for sure - but it doesn't have the layers of XML BS to reach the good old Java (the only XML conf I remember touching in .NET Core was when I had to configure IIS for Azure deploys).

I've left C# ecosystem 3 years ago because I was done with that as well, but then I landed in a mature Ruby on Rails project and I was crying for .NET "enterprisey" abstractions - once you see the code duplication that comes from the fat models and controllers, you have to grep the codebase and guess what happens in a function because it's in a mixin that assumes property exists in context, tests take forever to rerun because they bootstrap an entire environment and have no mocking. If I had to chose between a bad C# codebase or a bad RoR codebase if it's beyond something very simple I would chose C# one any day of the week - which is what I think C# approach gets you - guarantee that if you follow the conventions your project will scale reasonably well into maintainability and codebase size. You pay for that in initial development speed and pointless verbosity.

Re:.NET 5.0 by BatteryMountain on Wednesday November 11, 2020 @03:02AM (#25056413)
The forced DI pattern makes sense here because:

Most DI containers are not just injectors, but they also manage life cycles/scopes of objects: singleton/transient/scoped.

Since in web development, a request hitting a controller endpoint is typically short lived and most objects and services are tied to the main request scope, it makes sense that all your objects should live and die when the request is made and completed. What is the cleanest way to manage this life cycle scopes? Dependency Injection. Most of your object/services will be "scoped", with fewer being transient (aka a pool of reusable objects) and the fewest being singletons that will survive individual requests.

A second side effect of DI, it forces you to code by convention. Conventions make maintaining the code 6 months from now a breeze. Want to add a new service? Just let it inherit from an IService and consume it in 10 places, it will auto find/inject your new code. No need to new() up and dispose your service in 10 place.

Do all of this without DI and use only constructors + Dispose(). Good luck! Mercy on the poor soul who has to maintain all that mess.

If you want to go a step further, instead of having 100's of IService and each constructor declaring they each need 10 of them (ILoggerService, IAccountService, IEmailService, IStockService etc etc)... that also becomes very gross in large projects: so to go a step further, use the Mediator pattern. You can either implement your own (super easy) or use the Mediatr nuget package. Then each service becomes much cleaner. Each service then only has 1 method that does work. It also ties in nicely with the Unit of Work pattern.

Why should my IStockService inject the IEmailService when I just want to check stock levels with GetLatestStock() that return an int and does no other work?

Lets say the IStockService has 15 methods to do with stock and 10 dependencies. So on each request where you depend on IStockService, you would also pull in the 10 dependencies and their inner dependencies which may add 1 second to your response time and uses 10mb RAM. But all you wanted to was check stock which takes 10ms and 1mb RAM.

This is exactly the scenario that mediator pattern can help solve. So your 15 methods become 15 individual classes, each pulling in ONLY the dependencies it needs and nothing more. Your file and git commits stay small too which makes everything more digestible (less than 100 lines of code if lucky),

So my favourite setup is DI + Mediatr. Each file/class has only ONE purpose to exist and only one reason to be pulled into a dependency tree, all while DI will manage their life cycles.

Edit: For those downvoting, please go read "Dependency Injection by Mark Seemann" and also read https://docs.microsoft.com/en-us/aspnet/core/performance/per... . Then try to build your own framework from scratch. Do it. Then come crawl back and upvote this comment. I've have a ton of experience with this stuff and have built 2 or 3 custom frameworks. The core trait that keeps everything sane and fast is to keep things simple, keep dependencies low, keep hot paths lean. The easiest way to get to that place is DI + Mediatr and to break some services into their own api's if they get deployed too often. It's that simple.

Re:.NET 5.0 by Netcob on Wednesday November 11, 2020 @04:35AM (#25056930)
I totally agree. It took me a while to wrap my head around it, but my code has improved so much once I did. Very small classes that each do one easy to understand thing. All the structure stuff is in one part of the code, ready to be understood and modified, instead of scattered across tens of modules. Most of the time all I need for a new feature is a class that implements a specific interface, announces to the world what it needs to do its job by declaring its dependencies in the constructor (as intended by the language and OOP in general) and then only implements its core logic instead of meddling with creation and disposal that has nothing to do with its actual job.
Re:.NET 5.0 by garethrowlands on Wednesday November 11, 2020 @06:50AM (#25057578)
> Most DI containers are not just injectors, but they also manage life cycles/scopes of objects: singleton/transient/scoped.

That imperative lifecycle stuff is a big problem. Is that idiomatic in .net? Ideally, the program creates per-request data and then the garbage collector disposes of it after the end of the request (or earlier if it doesn't need to be retained until the end of the request). If you need to actually call Dispose, short of `using ...`, you have a problem.

> Lets say the IStockService has 15 methods to do with stock and 10 dependencies

Is this idiomatic in .net? It's obvious that that is a problem and that smaller classes/functions are better. Normally, your programming language and environment would let you create smaller classes/functions and call them as necessary. Why is something more complicated required in this context?

Re:.NET 5.0 by BatteryMountain on Wednesday November 11, 2020 @07:19AM (#25057734)
I'd say the IStockService with 15 methods and 10 dependencies are not a .net thing but rather <enterprizey-domain-driven-design-all-the-things-coolaid> thing. I've seen it in more than one shop and it totally makes sense why it comes into being.

DI just hides the problem because such a class is now only 500 lines long instead of 2000 lines, so for some people that is acceptable (not for me though). You don't see any lifecycle code in your classes anymore since the DI container manages it for them.

Remember it is typical to see a business project with 300 classes/tables if the project is about 5 years old and never seen a major refactor/rewrite, and each of those classes gets manipulated in some form from an orchestration point (xManager class or xService class), which in turn might depend on each other or have 10 inner dependencies. To keep things "simple" most guys would just add another method to an existing service where it seems to make the most sense.

I argue against that cause the services become heavier and heavier over time and can do allll sorts of things after 5 years (aka IStockService can now check stock, send email notification, generate invoice, save pdf to disk etc). So I've come to the conclusion its better to have more folders/files to contain handlers, and each handler only has one Execute/Process method, and it's constructor declaring only the minimum amount of dependencies to do it's work. It also encourages ALL your services to do only one thing: you know and can trust that IPdfDiskPersistor only does one thing and doesn't have other weird side effects (like trying to send an email).

If all this is really not clean enough, then maybe an ActorModel framework like Orleans Framework might be better suited, but I haven't been able to convince anyone at work to use it instead of DDD (they are slightly at odds with each other).

Hope that answers some of your questions. If other are reading this, please think twice before you go down the DDD path - it is expensive both in code and time and can easily spiral into a monster (but also well worth it if a good developer have stewardship of it in the long term - keyword being stewardship). Unfortunately teams with high turnover is basically doomed to have a messy/failed project.

Re:.NET 5.0 by girvo on Wednesday November 11, 2020 @12:22AM (#25055715)
Deno + express gives you the statically typed language you’ll enjoy with a Node-like runtime, for what it’s worth.
Re:.NET 5.0 by davidfowl on Tuesday November 10, 2020 @04:07PM (#25051920)
I can get behind the DI dislike, but how are callbacks and promises in nodejs better than async in .NET?
Re:.NET 5.0 by Xeronate on Tuesday November 10, 2020 @04:55PM (#25052519)
What’s not to like about DI? Makes it so much easier to wire up dependent services and refactor those wirings at a later time. If you don’t use DI you have to manually manage everything yourself.
Re:.NET 5.0 by charlieflowers on Tuesday November 10, 2020 @11:38PM (#25055533)
If you go too far with DI, the saying is "everything happens somewhere else."

Some feel it can be needlessly complex to troubleshoot such a system or gain understanding of it if you weren't one of the original authors.

Re:.NET 5.0 by Xeronate on Wednesday November 11, 2020 @02:25AM (#25056231)
Don't need DI to make your program so abstract no one can follow it. Wouldn't even say DI makes it easier to do because you can accomplish the same thing by just newing up objects.
Re:.NET 5.0 by WorldMaker on Wednesday November 11, 2020 @01:05PM (#25060923)
That's related to my rule of when DI is being abused: if you can't just new up the objects by hand (perhaps in a unit test somewhere), then you should rethink your use of DI.

I've seen projects where the dependency object graph exceeded anything you could possibly new up yourself, due to circular dependencies and impossibly complex scope rules. That's definitely a sign of a program so abstract no one can follow it.

(Microsoft's very simple DI container that's now standard out-of-the-box in .NET Core has somewhat strict limits on DI scopes and disallows circular dependencies, so it's one of the better ones.)

Re:.NET 5.0 by vosper on Tuesday November 10, 2020 @04:17PM (#25052049)
If you're writing modern nodeJS you're probably not using callbacks or promises (directly) anymore (or using promises a lot less than you used to - Promise.all and Promise.allSettled is about it for me, and that's not that often).

The async/await syntax is where it's at. Honestly it's a massive improvement over promises, which I hated reasoning about almost as much as callbacks :)

Re:.NET 5.0 by charlieflowers on Tuesday November 10, 2020 @05:18PM (#25052808)
And ... C# _invented_ the async/await syntax. Node, Rust, etc., were all inspired by what C# did.
Re:.NET 5.0 by dragonwriter on Tuesday November 10, 2020 @05:23PM (#25052884)
> If you're writing modern nodeJS you're probably not using callbacks or promises (directly) anymore

I get that some people prefer async/await (I actually find explicit Promises clear enough that I don't have any strong preference, myself), but why wouldn't you be using explicit callbacks, which in my JS experience (mostly frontend, but also fairly modern) are super common outside of promises, which is the only place where I see modern JS replacing exlicit callbacks with a different structure.

Re:.NET 5.0 by vosper on Tuesday November 10, 2020 @09:04PM (#25054779)
Yeah, callbacks are fine until you get a big stack of them (so-called “callback hell”). Promises were the touted solution to callback hell, async/await the touted solution to endless promises chaining. While async/await is (tasty) syntactic sugar for promises, I think it’s a real improvement over callbacks - it’s one less argument to every function (because of promises) and I think it’s easier to read: there tends to be less nesting.
Re:.NET 5.0 by dragonwriter on Wednesday November 11, 2020 @03:44AM (#25056645)
The weird thing about async/await is that it gets you out of deeply nested callbacks into, pretty much by definition, exactly equally deeply nested async function calls. The only thing that seems different is that it seems to be more common (but not any more or less supported, since you can obviously have named non-async functions and you can also have anonymous async functions) to call named functions in async/await and anonymous functions defined inline as callbacks with promises.
Re:.NET 5.0 by Scarbutt on Tuesday November 10, 2020 @12:16PM (#25048344)
Having been using express again recently, I'm seriously thinking of ditching the asp.net core stack despite my general preference for statically typed languages.

Why not typescript?

Re:.NET 5.0 by hu3 on Tuesday November 10, 2020 @03:25PM (#25051417)
I'm so glad I'm not alone. I adore C# and the .NET runtime is so convenient.

But the ASP.NET part feels bloated.

Is there a simpler .NET framework?

Re:.NET 5.0 by u7u7h on Wednesday November 11, 2020 @07:46AM (#25057853)
Feather HTTP https://github.com/featherhttp/framework. From the description: A lightweight low ceremony API for web services.
Re:.NET 5.0 by macca321 on Tuesday November 10, 2020 @04:25PM (#25052175)
Carter
Re:.NET 5.0 by hydraxis on Tuesday November 10, 2020 @04:15PM (#25052026)
I didn't use it recently but Nancy was quite good: https://nancyfx.org/
Re:.NET 5.0 by Xeronate on Tuesday November 10, 2020 @07:27PM (#25054062)
Nancy is dead https://github.com/NancyFx/Nancy. Archived and stated that it is no longer maintained.
Re:.NET 5.0 by kumarvvr on Tuesday November 10, 2020 @10:33PM (#25055226)
> the really poor async code

Very curious. Why do you think it is poor ? Are you comparing it against other languages or frameworks?

Re:.NET 5.0 by brainzap on Tuesday November 10, 2020 @12:08PM (#25048219)
alternatives?
Re:.NET 5.0 by davidspiess on Tuesday November 10, 2020 @12:28PM (#25048488)
F# with Giraffe, a functional ASP.NET core framework
Re:.NET 5.0 by wincy on Tuesday November 10, 2020 @12:14PM (#25048305)
Express with Typescript feels pretty good in my opinion.
Re:.NET 5.0 by cutler on Tuesday November 10, 2020 @10:04PM (#25055078)
I can understand the preference for Node.js if you want to free yourself from the shackles of static typing but to then bolt-on Typescript doesn't make sense given that C# is a genuine statically-typed language. Last I looked Kestrel also ran rings round Node.