ASP.NET MVC 5: Inject a repository into an IValidatableObject












0















I have a class that implements the IValidatableObject interface, in order to validate the incoming data introduced by the user. The problem is that in order to validate that data, I need to use a class that implements the data repository pattern, which is in another assembly. Something like this:



public class SelectedFilteringCriteria : IValidatableObject
{
private IFiltersRepository _filtersRepository;

public SelectedFilteringCriteria(IFiltersRepository filtersRepository)
{
_filtersRepository = filtersRepository;
}

public int? SelectedValue { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();

var valueOk = _filtersRepository.GetFilters().Any(
filter => filter.Value == SelectedValue
);

if (!valueOk)
{
results.Add(new ValidationResult("Not good :("));
}

return results;
}
}


The dependency container I'm using is Ninject. I would like to know if there's a way to tell MVC to inject the repository class into the IValidatableObject when it's going to be created.










share|improve this question

























  • so what is wrong with the code you posted? Are you looking for how to set up the ninject kernel/binding to make your code possible?

    – GregH
    Nov 14 '18 at 17:46











  • @GregH I even don't know if it's possible to make it work. Now, the repository class is configured in the NinjectWebCommon file and it's working properly when it comes to get injected into controllers, but I can't make it get injected into the class I posted, mostly because I don't instantiate that class, it's MVC which instantiates it with an incoming request. I would like to know how to get it injected into the class I posted.

    – amedina
    Nov 15 '18 at 7:47











  • It sounds like you may be going about this a little bit the wrong way. I think you want to inject an interface for the repo into the concrete class SelectedFilteringCriteria whereas you mentioned trying to inject it into an interface IValidatableObject. What is wrong with injecting your repo interface into the concrete class SelectedFilteringCriteria? This is how I've seen DI done time and time again. I'm not sure why you'd need to inject anything into an interface itself. Maybe some more context would help

    – GregH
    Nov 15 '18 at 13:03











  • if you have multiple classes which inherit from IValidatableObject and need your repo injected into each of them, then create a base class that your repo interface gets injected into and then have your other class(es) inherit from them. So the class signature would look something like SelectedFilteringCriteria : BaseCriteria, IValidatableObject where the repo is injected into BaseCriteria so that all classes which inherit from it have access to your repo

    – GregH
    Nov 15 '18 at 13:05













  • @GregH I didn't say I want to inject a class inside an interface, that's absurd. Ok, in simpler terms: FiltersRepository must be injected into SelectedFilteringCriteria via constructor. How can I achieve that having into account that it's not me, but MVC what instantiates the SelectedFilteringCriteria class. In summary: It's a configuration problem: How can I configure MVC and Ninject to achieve that?

    – amedina
    Nov 15 '18 at 13:35


















0















I have a class that implements the IValidatableObject interface, in order to validate the incoming data introduced by the user. The problem is that in order to validate that data, I need to use a class that implements the data repository pattern, which is in another assembly. Something like this:



public class SelectedFilteringCriteria : IValidatableObject
{
private IFiltersRepository _filtersRepository;

public SelectedFilteringCriteria(IFiltersRepository filtersRepository)
{
_filtersRepository = filtersRepository;
}

public int? SelectedValue { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();

var valueOk = _filtersRepository.GetFilters().Any(
filter => filter.Value == SelectedValue
);

if (!valueOk)
{
results.Add(new ValidationResult("Not good :("));
}

return results;
}
}


The dependency container I'm using is Ninject. I would like to know if there's a way to tell MVC to inject the repository class into the IValidatableObject when it's going to be created.










share|improve this question

























  • so what is wrong with the code you posted? Are you looking for how to set up the ninject kernel/binding to make your code possible?

    – GregH
    Nov 14 '18 at 17:46











  • @GregH I even don't know if it's possible to make it work. Now, the repository class is configured in the NinjectWebCommon file and it's working properly when it comes to get injected into controllers, but I can't make it get injected into the class I posted, mostly because I don't instantiate that class, it's MVC which instantiates it with an incoming request. I would like to know how to get it injected into the class I posted.

    – amedina
    Nov 15 '18 at 7:47











  • It sounds like you may be going about this a little bit the wrong way. I think you want to inject an interface for the repo into the concrete class SelectedFilteringCriteria whereas you mentioned trying to inject it into an interface IValidatableObject. What is wrong with injecting your repo interface into the concrete class SelectedFilteringCriteria? This is how I've seen DI done time and time again. I'm not sure why you'd need to inject anything into an interface itself. Maybe some more context would help

    – GregH
    Nov 15 '18 at 13:03











  • if you have multiple classes which inherit from IValidatableObject and need your repo injected into each of them, then create a base class that your repo interface gets injected into and then have your other class(es) inherit from them. So the class signature would look something like SelectedFilteringCriteria : BaseCriteria, IValidatableObject where the repo is injected into BaseCriteria so that all classes which inherit from it have access to your repo

    – GregH
    Nov 15 '18 at 13:05













  • @GregH I didn't say I want to inject a class inside an interface, that's absurd. Ok, in simpler terms: FiltersRepository must be injected into SelectedFilteringCriteria via constructor. How can I achieve that having into account that it's not me, but MVC what instantiates the SelectedFilteringCriteria class. In summary: It's a configuration problem: How can I configure MVC and Ninject to achieve that?

    – amedina
    Nov 15 '18 at 13:35
















0












0








0








I have a class that implements the IValidatableObject interface, in order to validate the incoming data introduced by the user. The problem is that in order to validate that data, I need to use a class that implements the data repository pattern, which is in another assembly. Something like this:



public class SelectedFilteringCriteria : IValidatableObject
{
private IFiltersRepository _filtersRepository;

public SelectedFilteringCriteria(IFiltersRepository filtersRepository)
{
_filtersRepository = filtersRepository;
}

public int? SelectedValue { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();

var valueOk = _filtersRepository.GetFilters().Any(
filter => filter.Value == SelectedValue
);

if (!valueOk)
{
results.Add(new ValidationResult("Not good :("));
}

return results;
}
}


The dependency container I'm using is Ninject. I would like to know if there's a way to tell MVC to inject the repository class into the IValidatableObject when it's going to be created.










share|improve this question
















I have a class that implements the IValidatableObject interface, in order to validate the incoming data introduced by the user. The problem is that in order to validate that data, I need to use a class that implements the data repository pattern, which is in another assembly. Something like this:



public class SelectedFilteringCriteria : IValidatableObject
{
private IFiltersRepository _filtersRepository;

public SelectedFilteringCriteria(IFiltersRepository filtersRepository)
{
_filtersRepository = filtersRepository;
}

public int? SelectedValue { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();

var valueOk = _filtersRepository.GetFilters().Any(
filter => filter.Value == SelectedValue
);

if (!valueOk)
{
results.Add(new ValidationResult("Not good :("));
}

return results;
}
}


The dependency container I'm using is Ninject. I would like to know if there's a way to tell MVC to inject the repository class into the IValidatableObject when it's going to be created.







asp.net-mvc asp.net-mvc-5 ninject ninject.web.mvc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 16:03







amedina

















asked Nov 14 '18 at 15:49









amedinaamedina

615411




615411













  • so what is wrong with the code you posted? Are you looking for how to set up the ninject kernel/binding to make your code possible?

    – GregH
    Nov 14 '18 at 17:46











  • @GregH I even don't know if it's possible to make it work. Now, the repository class is configured in the NinjectWebCommon file and it's working properly when it comes to get injected into controllers, but I can't make it get injected into the class I posted, mostly because I don't instantiate that class, it's MVC which instantiates it with an incoming request. I would like to know how to get it injected into the class I posted.

    – amedina
    Nov 15 '18 at 7:47











  • It sounds like you may be going about this a little bit the wrong way. I think you want to inject an interface for the repo into the concrete class SelectedFilteringCriteria whereas you mentioned trying to inject it into an interface IValidatableObject. What is wrong with injecting your repo interface into the concrete class SelectedFilteringCriteria? This is how I've seen DI done time and time again. I'm not sure why you'd need to inject anything into an interface itself. Maybe some more context would help

    – GregH
    Nov 15 '18 at 13:03











  • if you have multiple classes which inherit from IValidatableObject and need your repo injected into each of them, then create a base class that your repo interface gets injected into and then have your other class(es) inherit from them. So the class signature would look something like SelectedFilteringCriteria : BaseCriteria, IValidatableObject where the repo is injected into BaseCriteria so that all classes which inherit from it have access to your repo

    – GregH
    Nov 15 '18 at 13:05













  • @GregH I didn't say I want to inject a class inside an interface, that's absurd. Ok, in simpler terms: FiltersRepository must be injected into SelectedFilteringCriteria via constructor. How can I achieve that having into account that it's not me, but MVC what instantiates the SelectedFilteringCriteria class. In summary: It's a configuration problem: How can I configure MVC and Ninject to achieve that?

    – amedina
    Nov 15 '18 at 13:35





















  • so what is wrong with the code you posted? Are you looking for how to set up the ninject kernel/binding to make your code possible?

    – GregH
    Nov 14 '18 at 17:46











  • @GregH I even don't know if it's possible to make it work. Now, the repository class is configured in the NinjectWebCommon file and it's working properly when it comes to get injected into controllers, but I can't make it get injected into the class I posted, mostly because I don't instantiate that class, it's MVC which instantiates it with an incoming request. I would like to know how to get it injected into the class I posted.

    – amedina
    Nov 15 '18 at 7:47











  • It sounds like you may be going about this a little bit the wrong way. I think you want to inject an interface for the repo into the concrete class SelectedFilteringCriteria whereas you mentioned trying to inject it into an interface IValidatableObject. What is wrong with injecting your repo interface into the concrete class SelectedFilteringCriteria? This is how I've seen DI done time and time again. I'm not sure why you'd need to inject anything into an interface itself. Maybe some more context would help

    – GregH
    Nov 15 '18 at 13:03











  • if you have multiple classes which inherit from IValidatableObject and need your repo injected into each of them, then create a base class that your repo interface gets injected into and then have your other class(es) inherit from them. So the class signature would look something like SelectedFilteringCriteria : BaseCriteria, IValidatableObject where the repo is injected into BaseCriteria so that all classes which inherit from it have access to your repo

    – GregH
    Nov 15 '18 at 13:05













  • @GregH I didn't say I want to inject a class inside an interface, that's absurd. Ok, in simpler terms: FiltersRepository must be injected into SelectedFilteringCriteria via constructor. How can I achieve that having into account that it's not me, but MVC what instantiates the SelectedFilteringCriteria class. In summary: It's a configuration problem: How can I configure MVC and Ninject to achieve that?

    – amedina
    Nov 15 '18 at 13:35



















so what is wrong with the code you posted? Are you looking for how to set up the ninject kernel/binding to make your code possible?

– GregH
Nov 14 '18 at 17:46





so what is wrong with the code you posted? Are you looking for how to set up the ninject kernel/binding to make your code possible?

– GregH
Nov 14 '18 at 17:46













@GregH I even don't know if it's possible to make it work. Now, the repository class is configured in the NinjectWebCommon file and it's working properly when it comes to get injected into controllers, but I can't make it get injected into the class I posted, mostly because I don't instantiate that class, it's MVC which instantiates it with an incoming request. I would like to know how to get it injected into the class I posted.

– amedina
Nov 15 '18 at 7:47





@GregH I even don't know if it's possible to make it work. Now, the repository class is configured in the NinjectWebCommon file and it's working properly when it comes to get injected into controllers, but I can't make it get injected into the class I posted, mostly because I don't instantiate that class, it's MVC which instantiates it with an incoming request. I would like to know how to get it injected into the class I posted.

– amedina
Nov 15 '18 at 7:47













It sounds like you may be going about this a little bit the wrong way. I think you want to inject an interface for the repo into the concrete class SelectedFilteringCriteria whereas you mentioned trying to inject it into an interface IValidatableObject. What is wrong with injecting your repo interface into the concrete class SelectedFilteringCriteria? This is how I've seen DI done time and time again. I'm not sure why you'd need to inject anything into an interface itself. Maybe some more context would help

– GregH
Nov 15 '18 at 13:03





It sounds like you may be going about this a little bit the wrong way. I think you want to inject an interface for the repo into the concrete class SelectedFilteringCriteria whereas you mentioned trying to inject it into an interface IValidatableObject. What is wrong with injecting your repo interface into the concrete class SelectedFilteringCriteria? This is how I've seen DI done time and time again. I'm not sure why you'd need to inject anything into an interface itself. Maybe some more context would help

– GregH
Nov 15 '18 at 13:03













if you have multiple classes which inherit from IValidatableObject and need your repo injected into each of them, then create a base class that your repo interface gets injected into and then have your other class(es) inherit from them. So the class signature would look something like SelectedFilteringCriteria : BaseCriteria, IValidatableObject where the repo is injected into BaseCriteria so that all classes which inherit from it have access to your repo

– GregH
Nov 15 '18 at 13:05







if you have multiple classes which inherit from IValidatableObject and need your repo injected into each of them, then create a base class that your repo interface gets injected into and then have your other class(es) inherit from them. So the class signature would look something like SelectedFilteringCriteria : BaseCriteria, IValidatableObject where the repo is injected into BaseCriteria so that all classes which inherit from it have access to your repo

– GregH
Nov 15 '18 at 13:05















@GregH I didn't say I want to inject a class inside an interface, that's absurd. Ok, in simpler terms: FiltersRepository must be injected into SelectedFilteringCriteria via constructor. How can I achieve that having into account that it's not me, but MVC what instantiates the SelectedFilteringCriteria class. In summary: It's a configuration problem: How can I configure MVC and Ninject to achieve that?

– amedina
Nov 15 '18 at 13:35







@GregH I didn't say I want to inject a class inside an interface, that's absurd. Ok, in simpler terms: FiltersRepository must be injected into SelectedFilteringCriteria via constructor. How can I achieve that having into account that it's not me, but MVC what instantiates the SelectedFilteringCriteria class. In summary: It's a configuration problem: How can I configure MVC and Ninject to achieve that?

– amedina
Nov 15 '18 at 13:35














1 Answer
1






active

oldest

votes


















0














Nope, it seems it's not possible because the MutableObjectModelBinder class, which is the one MVC 5 uses to create the corresponding object (SelectedFilteringCriteria in my case) from the action parameters, uses System.Activator instead of resolving the dependencies SelectedFilteringCriteria could have using the current DependencyResolver.



A workaround for this could be to do this inside the constructor of SelectedFilteringCriteria:



public SelectedFilteringCriteria()
{
_filtersRepository = DependencyResolver.Current.GetService<IFiltersRepository>();
}


But that could drive to the Service Locator Antipattern. Your choice.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53304004%2fasp-net-mvc-5-inject-a-repository-into-an-ivalidatableobject%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Nope, it seems it's not possible because the MutableObjectModelBinder class, which is the one MVC 5 uses to create the corresponding object (SelectedFilteringCriteria in my case) from the action parameters, uses System.Activator instead of resolving the dependencies SelectedFilteringCriteria could have using the current DependencyResolver.



    A workaround for this could be to do this inside the constructor of SelectedFilteringCriteria:



    public SelectedFilteringCriteria()
    {
    _filtersRepository = DependencyResolver.Current.GetService<IFiltersRepository>();
    }


    But that could drive to the Service Locator Antipattern. Your choice.






    share|improve this answer




























      0














      Nope, it seems it's not possible because the MutableObjectModelBinder class, which is the one MVC 5 uses to create the corresponding object (SelectedFilteringCriteria in my case) from the action parameters, uses System.Activator instead of resolving the dependencies SelectedFilteringCriteria could have using the current DependencyResolver.



      A workaround for this could be to do this inside the constructor of SelectedFilteringCriteria:



      public SelectedFilteringCriteria()
      {
      _filtersRepository = DependencyResolver.Current.GetService<IFiltersRepository>();
      }


      But that could drive to the Service Locator Antipattern. Your choice.






      share|improve this answer


























        0












        0








        0







        Nope, it seems it's not possible because the MutableObjectModelBinder class, which is the one MVC 5 uses to create the corresponding object (SelectedFilteringCriteria in my case) from the action parameters, uses System.Activator instead of resolving the dependencies SelectedFilteringCriteria could have using the current DependencyResolver.



        A workaround for this could be to do this inside the constructor of SelectedFilteringCriteria:



        public SelectedFilteringCriteria()
        {
        _filtersRepository = DependencyResolver.Current.GetService<IFiltersRepository>();
        }


        But that could drive to the Service Locator Antipattern. Your choice.






        share|improve this answer













        Nope, it seems it's not possible because the MutableObjectModelBinder class, which is the one MVC 5 uses to create the corresponding object (SelectedFilteringCriteria in my case) from the action parameters, uses System.Activator instead of resolving the dependencies SelectedFilteringCriteria could have using the current DependencyResolver.



        A workaround for this could be to do this inside the constructor of SelectedFilteringCriteria:



        public SelectedFilteringCriteria()
        {
        _filtersRepository = DependencyResolver.Current.GetService<IFiltersRepository>();
        }


        But that could drive to the Service Locator Antipattern. Your choice.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 15 '18 at 16:02









        amedinaamedina

        615411




        615411
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53304004%2fasp-net-mvc-5-inject-a-repository-into-an-ivalidatableobject%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Error while running script in elastic search , gateway timeout

            Adding quotations to stringified JSON object values