Steve Cross
Steve Cross

Reputation: 95

How can I initialize a repository in a static class?

I need a static class to use in multiple places. I need to inject a dependency, but I can't quite figure out how to do this. Here is a few (combined) of my tries. I know this is probably a simple fix, but I can't quite figure it out.

public static class Utility
{
    private static IBrandRepository _brandRepository;
    private static IModelRepository _modelRepository;
    static Utility()
    {
        _brandRepository = BrandRepository; // Actually calling the repository doesn't work.
        _modelRepository = modelRepository; // This was when I tried to add the parameter but static constructors must be parameter free.
    }
    public static IEnumerable<T_IFS_BrandDTO> GetBrands(int categoryID)
    {
        // Gets all the Brands for the given Category
        var sendBrands = BrandRepository.GetAllByCategory(categoryID); // Tried to call the repo directly with no joy.
        return sendBrands;
    }
    public static IEnumerable<T_IFS_ModelDTO> GetModels(int brandID, int categoryID)
    {
        // Gets all the Models for the given Category and Brand
        return _modelRepository.GetAllByBrand(brandID, categoryID); This was when I attempted the standard way of dependency injection.
    }

}

Upvotes: 0

Views: 211

Answers (1)

Steve Cross
Steve Cross

Reputation: 95

I was able to determine what I needed from this post:

How to inject dependency to static class

Upvotes: 0

Related Questions