简体   繁体   中英

Define global variable in _ViewImports.cshtml

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM