Shared data and shared methods in .NET Core Razor

asp.net-core c# entity-framework-core razor

Question

I am new to C# and .NET and am about to create a little CRUD project based on .NET Core 2.1, EF 2.1 and Razor pages.

I have this very basic question:

I need some basic methods and some basic data in many of my cshtml.cs controllers and I want to create one central place to define them. Which is the recommended way to do that?

I envision one or more static classes with static properties to provide common data for the controllers, and with methods that can be used by all controllers. But is this the recommended solution? And in which folder of the project should I place them? Any naming conventions would be appreciated too.

An example for central data I want to store is a dictionary of database errors like this:

    Dictionary<int, string> _sqlErrorTextDict = new Dictionary<int, string>
    {
        {547,
            "This operation failed because another data entry uses this entry."},
        {2601,
            "One of the properties is marked as Unique index and there is already an entry with that value."}
    };

An example for a central method would be code that receives a DB error exception object and creates a list of error text messages from it, ready to be displayed in any view.

1
1
5/3/2018 10:56:09 PM

Accepted Answer

You can use singletons for this. Here is a simple implementation based on your example:

First, create a class for storing the values. Your class could have any definition you find fit for your values. I am using this structure to stay closest to your code:

class CommonData : Dictionary<int, string>
{

}

In your startup.cs class you could use this:

services.AddSingleton(new CommonData {
    {547,
        "This operation failed because another data entry uses this entry."},
    {2601,
        "One of the properties is marked as Unique index and there is already an entry with that value."}
});

If you have too much data and would like to reduce the code on this file, you an create an extension function for this.

Within your controllers (and other services), you can use dependency injection to access this data:

private readonly CommonData commonData;
public HomeController(CommonData commonData)
{
    this.commonData = commonData;
}
2
4/27/2018 8:40:56 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow