Search code examples
c#.net-corestatic-classes

What is best practice to have a helper class in ASP.NET Core that can be used in all views?


How can I have a helper for something like site logo, site name and things like that?

I was thinking of a static helper class like SiteUtilities. But I need to have a cache system and access to database since this data may change.

Should I use another way?

Or if I can use a static helper, how can I inject my DbContext or repository into this class safely?

Sorry I know this is a kinda noobish questions, but I can't choose and something tells me that static isn't a good way to go.


Solution

  • If you need to use other dependencies, like other services or DB context, you really would need another interface and its implementation.

    For example IService and its implementation Service. Then you need to add it to service collection: services.AddScoped<IService, Service>().

    Then to inject DbContext or other repository, you just use constructor injection:

    public Service(DbContext context, IRepository repository)
    {
        _context = context;
        _repository = repository;
    }
    

    Then, if you need this class to handle some UI-related stuff, you can inject it directly to razor view:

    @inject IService Service
    

    Dependency injection into views in ASP.NET Core