I am using .NET 6.0. I want to define a global variable in _ViewImports.cshtml so that all other views can access it.
I encountered the following error
InvalidOperationException: No service for type 'System.String' has been registered.
SS
The following code:
`
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
string globalVariable = "text";
}
@inject string globalVariable;
`
I made no edits to the program.cs file, which came by default. By the way, I get similar errors for other types like int instead of string. I think program.cs also needs editing. Does anyone know what I should do ?
I tried methods like builder.Services.AddMvc() in program.cs.
CodePudding user response:
You do not need to use Dependency Injection to use global variables. Just declare a static class:
namespace SomeNamespace{
public class GlobalVariables
{
public static string globalVariable= "text";
}
}
And then anywhere in cshtml files:
@SomeNamespace.GlobalVariables.globalVariable
Alternatively, if you insist on using DI, you can define the class with non static declaration, create instance and add it as singleton to DI and then inject it like this:
public class GlobalVariablesNonStatic
{
public string GlobalVariable1{ get; set;}
}
Then in program.cs
var globalVariablesNonStaticInstance=new GlobalVariablesNonStatic();
globalVariablesNonStaticInstance.GlobalVariable1="Some value";
builder.Services.AddSingleton<GlobalVariablesNonStatic>(globalVariablesNonStaticInstance);
and then inject and use like this in cshtml file:
@inject GlobalVariablesNonStatic globalVars;