C
C#ā€¢8mo ago
DeathlyBower959

Blazor Services

I dont know too much blazor, but I have a .cs file in a /Settings folder, in which I would like to access a service which is storing state. (The service called State is stored in /Appearance). In razor components, i can just use @inject State state, and then access and modify it using state.<prop> How can i do the same inside of a standard c# file?
4 Replies
DeathlyBower959
DeathlyBower959ā€¢8mo ago
(ping if replying)
x0rld
x0rldā€¢8mo ago
you want to change a property in your State right ? šŸ¤” @DeathlyBower959 just add in any ctor your State to inject it and modify it
DeathlyBower959
DeathlyBower959ā€¢8mo ago
i think so yea this is my ThemeState.cs
public class ThemeState
{
public CssBuilder ThemeCSS { get; set; }
public event Action OnChange;

public ThemeState() { ThemeCSS = CssBuilder.FromFile(ThemePath, ":root"); }

public static readonly string WWWRootPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "wwwroot");

public static readonly string ThemePath = Path.Combine(WWWRootPath, "css", "theme.css");

public void ApplyTheme(CssBuilder css)
{
ThemeCSS = css;
OnChange?.Invoke();
}

public void UpdateTheme(string property, string value)
{
ThemeCSS.SetProperty(property, value);
OnChange?.Invoke();
}
}
public class ThemeState
{
public CssBuilder ThemeCSS { get; set; }
public event Action OnChange;

public ThemeState() { ThemeCSS = CssBuilder.FromFile(ThemePath, ":root"); }

public static readonly string WWWRootPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "wwwroot");

public static readonly string ThemePath = Path.Combine(WWWRootPath, "css", "theme.css");

public void ApplyTheme(CssBuilder css)
{
ThemeCSS = css;
OnChange?.Invoke();
}

public void UpdateTheme(string property, string value)
{
ThemeCSS.SetProperty(property, value);
OnChange?.Invoke();
}
}
its a simple state and i have added it to my services in MainWindow.xaml.cs
services.AddSingleton<ThemeState>();

Resources.Add("services", services.BuildServiceProvider());
services.AddSingleton<ThemeState>();

Resources.Add("services", services.BuildServiceProvider());
Im trying to access it in a .cs file, but im having some trouble
private readonly ThemeState _state;

public MyClass(ThemeState state = null)
{
_state = state;
}
private readonly ThemeState _state;

public MyClass(ThemeState state = null)
{
_state = state;
}
i tried this but its always null (i have to set a default value because i initialize this class to get default values)
Joschi
Joschiā€¢8mo ago
If you initialize a class yourself like with new MyClass() you would need to provide the dependency yourself. Automated DI only works if the framework creates something for your, like a razor component. So you would need access to the underlying service provider and use something like public static T? GetService<T> (this IServiceProvider provider);