Using IHtmlHelper with Dependency Injection Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!How to use ternary operator in razor (specifically on HTML attributes)?Calling an action of another controller and getting view as a stringSitecore MVC ViewRendereing and GlassMapperSending to different Pages depending on Web.config RazorASP.NET 5 Website (Razor)Return Razor partial View as JsonResult, ASP.NET MVC 5Custom Html helpers generate html via a view .cshtml fileJavascript in a View ComponentAuto inject javascript in blazor applicationhow to create one controller and multiple view in mvc 5

Why don't the Weasley twins use magic outside of school if the Trace can only find the location of spells cast?

Can inflation occur in a positive-sum game currency system such as the Stack Exchange reputation system?

What happens to sewage if there is no river near by?

Why aren't air breathing engines used as small first stages

Super Attribute Position on Product Page Magento 1

Diagram with tikz

Disable hyphenation for an entire paragraph

Do you forfeit tax refunds/credits if you aren't required to and don't file by April 15?

What do you call a phrase that's not an idiom yet?

Dating a Former Employee

How does a Death Domain cleric's Touch of Death feature work with Touch-range spells delivered by familiars?

Does accepting a pardon have any bearing on trying that person for the same crime in a sovereign jurisdiction?

Is there any avatar supposed to be born between the death of Krishna and the birth of Kalki?

Storing hydrofluoric acid before the invention of plastics

Is the Standard Deduction better than Itemized when both are the same amount?

Is the address of a local variable a constexpr?

Did Xerox really develop the first LAN?

What is a Meta algorithm?

How to deal with a team lead who never gives me credit?

Is a manifold-with-boundary with given interior and non-empty boundary essentially unique?

Can a non-EU citizen traveling with me come with me through the EU passport line?

Why does Python start at index -1 when indexing a list from the end?

Models of set theory where not every set can be linearly ordered

How can I fade player character when he goes inside or outside of the area?



Using IHtmlHelper with Dependency Injection



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!How to use ternary operator in razor (specifically on HTML attributes)?Calling an action of another controller and getting view as a stringSitecore MVC ViewRendereing and GlassMapperSending to different Pages depending on Web.config RazorASP.NET 5 Website (Razor)Return Razor partial View as JsonResult, ASP.NET MVC 5Custom Html helpers generate html via a view .cshtml fileJavascript in a View ComponentAuto inject javascript in blazor applicationhow to create one controller and multiple view in mvc 5



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I would create a controller that response with the third-party IHtmlContent created through IHtmlHelper interface without using View() method. Actually I'm using a workaround:



I have created an extension function of IHtmlHelper that behaves like a "master" and other static function that behaves like "slaves". The master function call slaves based on data structure that It has received as a parameter. Slaves create the IHtmlContent based on third-party library. When all slave functions are completed, the controller send back the response.
This behaviour is inside cshtml view called by controller.



Is possible to have IHtmlHelper as controller constructor parameter using dependency Injection?



Something like



public class MyTestController 

private readonly IHtmlHelper _html;

public MyTestController(IHtmlHelper html)
_html = html;




If it were possible I would simplify many operations because I'm using this Master/Slave functions to replicate the behaviours of a class



Here you can find a pure example of how my code works now and how I would like to change it
https://gist.github.com/Blackleones/eb0d02b9dd99164271af88e22143d72b#file-example-cs



I need this component because the third-party library is an extension of IHtmlHelper










share|improve this question



















  • 1





    I don't understand why you would want (or need) this component in the controller.

    – DavidG
    Mar 8 at 16:43











  • Hi DavidG. I created an example on Gists to explain why I would like to have this component. The code that you will see is a pure example that emulate what I would like to do. gist.github.com/Blackleones/…

    – Leonardo Lurci
    Mar 8 at 17:11












  • DavidG I need this component because the third party library is an extension of IHtmlHelper

    – Leonardo Lurci
    Mar 8 at 18:49

















2















I would create a controller that response with the third-party IHtmlContent created through IHtmlHelper interface without using View() method. Actually I'm using a workaround:



I have created an extension function of IHtmlHelper that behaves like a "master" and other static function that behaves like "slaves". The master function call slaves based on data structure that It has received as a parameter. Slaves create the IHtmlContent based on third-party library. When all slave functions are completed, the controller send back the response.
This behaviour is inside cshtml view called by controller.



Is possible to have IHtmlHelper as controller constructor parameter using dependency Injection?



Something like



public class MyTestController 

private readonly IHtmlHelper _html;

public MyTestController(IHtmlHelper html)
_html = html;




If it were possible I would simplify many operations because I'm using this Master/Slave functions to replicate the behaviours of a class



Here you can find a pure example of how my code works now and how I would like to change it
https://gist.github.com/Blackleones/eb0d02b9dd99164271af88e22143d72b#file-example-cs



I need this component because the third-party library is an extension of IHtmlHelper










share|improve this question



















  • 1





    I don't understand why you would want (or need) this component in the controller.

    – DavidG
    Mar 8 at 16:43











  • Hi DavidG. I created an example on Gists to explain why I would like to have this component. The code that you will see is a pure example that emulate what I would like to do. gist.github.com/Blackleones/…

    – Leonardo Lurci
    Mar 8 at 17:11












  • DavidG I need this component because the third party library is an extension of IHtmlHelper

    – Leonardo Lurci
    Mar 8 at 18:49













2












2








2








I would create a controller that response with the third-party IHtmlContent created through IHtmlHelper interface without using View() method. Actually I'm using a workaround:



I have created an extension function of IHtmlHelper that behaves like a "master" and other static function that behaves like "slaves". The master function call slaves based on data structure that It has received as a parameter. Slaves create the IHtmlContent based on third-party library. When all slave functions are completed, the controller send back the response.
This behaviour is inside cshtml view called by controller.



Is possible to have IHtmlHelper as controller constructor parameter using dependency Injection?



Something like



public class MyTestController 

private readonly IHtmlHelper _html;

public MyTestController(IHtmlHelper html)
_html = html;




If it were possible I would simplify many operations because I'm using this Master/Slave functions to replicate the behaviours of a class



Here you can find a pure example of how my code works now and how I would like to change it
https://gist.github.com/Blackleones/eb0d02b9dd99164271af88e22143d72b#file-example-cs



I need this component because the third-party library is an extension of IHtmlHelper










share|improve this question
















I would create a controller that response with the third-party IHtmlContent created through IHtmlHelper interface without using View() method. Actually I'm using a workaround:



I have created an extension function of IHtmlHelper that behaves like a "master" and other static function that behaves like "slaves". The master function call slaves based on data structure that It has received as a parameter. Slaves create the IHtmlContent based on third-party library. When all slave functions are completed, the controller send back the response.
This behaviour is inside cshtml view called by controller.



Is possible to have IHtmlHelper as controller constructor parameter using dependency Injection?



Something like



public class MyTestController 

private readonly IHtmlHelper _html;

public MyTestController(IHtmlHelper html)
_html = html;




If it were possible I would simplify many operations because I'm using this Master/Slave functions to replicate the behaviours of a class



Here you can find a pure example of how my code works now and how I would like to change it
https://gist.github.com/Blackleones/eb0d02b9dd99164271af88e22143d72b#file-example-cs



I need this component because the third-party library is an extension of IHtmlHelper







asp.net-core razor






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 5:33









marc_s

585k13011261272




585k13011261272










asked Mar 8 at 16:34









Leonardo LurciLeonardo Lurci

407




407







  • 1





    I don't understand why you would want (or need) this component in the controller.

    – DavidG
    Mar 8 at 16:43











  • Hi DavidG. I created an example on Gists to explain why I would like to have this component. The code that you will see is a pure example that emulate what I would like to do. gist.github.com/Blackleones/…

    – Leonardo Lurci
    Mar 8 at 17:11












  • DavidG I need this component because the third party library is an extension of IHtmlHelper

    – Leonardo Lurci
    Mar 8 at 18:49












  • 1





    I don't understand why you would want (or need) this component in the controller.

    – DavidG
    Mar 8 at 16:43











  • Hi DavidG. I created an example on Gists to explain why I would like to have this component. The code that you will see is a pure example that emulate what I would like to do. gist.github.com/Blackleones/…

    – Leonardo Lurci
    Mar 8 at 17:11












  • DavidG I need this component because the third party library is an extension of IHtmlHelper

    – Leonardo Lurci
    Mar 8 at 18:49







1




1





I don't understand why you would want (or need) this component in the controller.

– DavidG
Mar 8 at 16:43





I don't understand why you would want (or need) this component in the controller.

– DavidG
Mar 8 at 16:43













Hi DavidG. I created an example on Gists to explain why I would like to have this component. The code that you will see is a pure example that emulate what I would like to do. gist.github.com/Blackleones/…

– Leonardo Lurci
Mar 8 at 17:11






Hi DavidG. I created an example on Gists to explain why I would like to have this component. The code that you will see is a pure example that emulate what I would like to do. gist.github.com/Blackleones/…

– Leonardo Lurci
Mar 8 at 17:11














DavidG I need this component because the third party library is an extension of IHtmlHelper

– Leonardo Lurci
Mar 8 at 18:49





DavidG I need this component because the third party library is an extension of IHtmlHelper

– Leonardo Lurci
Mar 8 at 18:49












2 Answers
2






active

oldest

votes


















1














Short answer : Yes .




If you look into the source code of MVC, you will find that the IHtmlHelper is registered as a transient service :



 internal static void AddViewServices(IServiceCollection services)


...

//
// HTML Helper
//
services.TryAddTransient<IHtmlHelper, HtmlHelper>();
services.TryAddTransient(typeof(IHtmlHelper<>), typeof(HtmlHelper<>));
services.TryAddSingleton<IHtmlGenerator, DefaultHtmlGenerator>();
services.TryAddSingleton<ModelExpressionProvider>();
// ModelExpressionProvider caches results. Ensure that it's re-used when the requested type is IModelExpressionProvider.
services.TryAddSingleton<IModelExpressionProvider>(s => s.GetRequiredService<ModelExpressionProvider>());
services.TryAddSingleton<ValidationHtmlAttributeProvider, DefaultValidationHtmlAttributeProvider>();

services.TryAddSingleton<IJsonHelper, DefaultJsonHelper>();

...




In other words, you could inject the IHtmlHelper service as you like.



Just as a reminder, we should always prefer to using IHtmlHelper within View Layer.






share|improve this answer
































    1














    I thank Itminus for answering me.



    However call IHtmlHelper on controller constructor it is not enough, you must contextualize IHtmlHelper before using it.



    I want to share another solution that I found and solve my problem, maybe It can be useful for other users.
    Please see https://gist.github.com/Blackleones/eb0d02b9dd99164271af88e22143d72b#file-example-cs to remember what my goal is.



    1. To solve my problem I have created a class called HtmlHelperAdapter that contains some instances I need.

    public class MyHtmlHelperAdapter

    public IHtmlHelper _html;

    public NubessHtmlHelperAdapter(IHtmlHelper html)

    _html = html;


    public IHtmlHelper Html => _html;
    public ViewContext ViewContext => _html.ViewContext;
    public HttpContext HttpContext => _html.ViewContext.HttpContext;
    public ViewDataDictionary ViewData => _html.ViewData;
    public IServiceProvider provider => _html.ViewContext.HttpContext.RequestServices;



    1. after that I have created an extension method for IHtmlHelper

    public static class MyBuilderExtension

    public static MyBuilder Nubess(this IHtmlHelper html)

    return new MyBuilder(new MyHtmlHelperAdapter(html));




    where MyBuilder is



    public class MyBuilder

    private readonly MyHtmlHelperAdapter _htmlHelper;

    public MyBuilder(MyHtmlHelperAdapter htmlHelper)

    _htmlHelper = htmlHelper;


    public FormBuilder<object> Form<T>(IDictionary<string, string> customizeArgs = null, FormBuilder<object> externalForm = null)

    return new FormBuilder(_htmlHelper, typeof(T), customizeArgs, externalForm).Build();




    1. now I can create my custom contents for views using class thanks to MyHtmlHelperAdapter

     public class FormBuilder

    private MyHtmlHelperAdapter _htmlHelper;
    private readonly IStringLocalizer<SharedResources> _localizer;
    private readonly LinkGenerator _linkGenerator;
    private readonly IEngine _engine;
    private readonly IEngineElement _element;
    private readonly Type _typeDescriptor;
    private readonly IDictionary<string, string> _descriptorArgs;

    /* variabili per semplificare la gestione del builder */
    private readonly FormBuilder<object> Form;
    private readonly FormConfig Config;
    private readonly IList<FormGroupConfig> Groups;
    private readonly IList<FormItemConfig> Items;
    private readonly IDictionary<string, string> FormOptions;

    private readonly string _clientPrefix = "smtForm_0_";

    public FormBuilder(MyHtmlHelperAdapter htmlHelper, Type typeDescriptor, IDictionary<string, string> ModelCustomizeArgs = null, FormBuilder<object> externalForm = null)

    _htmlHelper = htmlHelper;
    _localizer = _htmlHelper.provider.GetRequiredService<IStringLocalizer<SharedResources>>() ?? throw new ArgumentNullException();
    _linkGenerator = _htmlHelper.provider.GetRequiredService<LinkGenerator>() ?? throw new ArgumentNullException();
    _engine = _htmlHelper.provider.GetRequiredService<IEngine>() ?? throw new ArgumentNullException();

    //code..



    public FormBuilder<object> Build()

    //code..
    return Form;


    //methods..






    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%2f55067308%2fusing-ihtmlhelper-with-dependency-injection%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Short answer : Yes .




      If you look into the source code of MVC, you will find that the IHtmlHelper is registered as a transient service :



       internal static void AddViewServices(IServiceCollection services)


      ...

      //
      // HTML Helper
      //
      services.TryAddTransient<IHtmlHelper, HtmlHelper>();
      services.TryAddTransient(typeof(IHtmlHelper<>), typeof(HtmlHelper<>));
      services.TryAddSingleton<IHtmlGenerator, DefaultHtmlGenerator>();
      services.TryAddSingleton<ModelExpressionProvider>();
      // ModelExpressionProvider caches results. Ensure that it's re-used when the requested type is IModelExpressionProvider.
      services.TryAddSingleton<IModelExpressionProvider>(s => s.GetRequiredService<ModelExpressionProvider>());
      services.TryAddSingleton<ValidationHtmlAttributeProvider, DefaultValidationHtmlAttributeProvider>();

      services.TryAddSingleton<IJsonHelper, DefaultJsonHelper>();

      ...




      In other words, you could inject the IHtmlHelper service as you like.



      Just as a reminder, we should always prefer to using IHtmlHelper within View Layer.






      share|improve this answer





























        1














        Short answer : Yes .




        If you look into the source code of MVC, you will find that the IHtmlHelper is registered as a transient service :



         internal static void AddViewServices(IServiceCollection services)


        ...

        //
        // HTML Helper
        //
        services.TryAddTransient<IHtmlHelper, HtmlHelper>();
        services.TryAddTransient(typeof(IHtmlHelper<>), typeof(HtmlHelper<>));
        services.TryAddSingleton<IHtmlGenerator, DefaultHtmlGenerator>();
        services.TryAddSingleton<ModelExpressionProvider>();
        // ModelExpressionProvider caches results. Ensure that it's re-used when the requested type is IModelExpressionProvider.
        services.TryAddSingleton<IModelExpressionProvider>(s => s.GetRequiredService<ModelExpressionProvider>());
        services.TryAddSingleton<ValidationHtmlAttributeProvider, DefaultValidationHtmlAttributeProvider>();

        services.TryAddSingleton<IJsonHelper, DefaultJsonHelper>();

        ...




        In other words, you could inject the IHtmlHelper service as you like.



        Just as a reminder, we should always prefer to using IHtmlHelper within View Layer.






        share|improve this answer



























          1












          1








          1







          Short answer : Yes .




          If you look into the source code of MVC, you will find that the IHtmlHelper is registered as a transient service :



           internal static void AddViewServices(IServiceCollection services)


          ...

          //
          // HTML Helper
          //
          services.TryAddTransient<IHtmlHelper, HtmlHelper>();
          services.TryAddTransient(typeof(IHtmlHelper<>), typeof(HtmlHelper<>));
          services.TryAddSingleton<IHtmlGenerator, DefaultHtmlGenerator>();
          services.TryAddSingleton<ModelExpressionProvider>();
          // ModelExpressionProvider caches results. Ensure that it's re-used when the requested type is IModelExpressionProvider.
          services.TryAddSingleton<IModelExpressionProvider>(s => s.GetRequiredService<ModelExpressionProvider>());
          services.TryAddSingleton<ValidationHtmlAttributeProvider, DefaultValidationHtmlAttributeProvider>();

          services.TryAddSingleton<IJsonHelper, DefaultJsonHelper>();

          ...




          In other words, you could inject the IHtmlHelper service as you like.



          Just as a reminder, we should always prefer to using IHtmlHelper within View Layer.






          share|improve this answer















          Short answer : Yes .




          If you look into the source code of MVC, you will find that the IHtmlHelper is registered as a transient service :



           internal static void AddViewServices(IServiceCollection services)


          ...

          //
          // HTML Helper
          //
          services.TryAddTransient<IHtmlHelper, HtmlHelper>();
          services.TryAddTransient(typeof(IHtmlHelper<>), typeof(HtmlHelper<>));
          services.TryAddSingleton<IHtmlGenerator, DefaultHtmlGenerator>();
          services.TryAddSingleton<ModelExpressionProvider>();
          // ModelExpressionProvider caches results. Ensure that it's re-used when the requested type is IModelExpressionProvider.
          services.TryAddSingleton<IModelExpressionProvider>(s => s.GetRequiredService<ModelExpressionProvider>());
          services.TryAddSingleton<ValidationHtmlAttributeProvider, DefaultValidationHtmlAttributeProvider>();

          services.TryAddSingleton<IJsonHelper, DefaultJsonHelper>();

          ...




          In other words, you could inject the IHtmlHelper service as you like.



          Just as a reminder, we should always prefer to using IHtmlHelper within View Layer.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 11 at 10:20

























          answered Mar 11 at 10:15









          itminusitminus

          4,6231424




          4,6231424























              1














              I thank Itminus for answering me.



              However call IHtmlHelper on controller constructor it is not enough, you must contextualize IHtmlHelper before using it.



              I want to share another solution that I found and solve my problem, maybe It can be useful for other users.
              Please see https://gist.github.com/Blackleones/eb0d02b9dd99164271af88e22143d72b#file-example-cs to remember what my goal is.



              1. To solve my problem I have created a class called HtmlHelperAdapter that contains some instances I need.

              public class MyHtmlHelperAdapter

              public IHtmlHelper _html;

              public NubessHtmlHelperAdapter(IHtmlHelper html)

              _html = html;


              public IHtmlHelper Html => _html;
              public ViewContext ViewContext => _html.ViewContext;
              public HttpContext HttpContext => _html.ViewContext.HttpContext;
              public ViewDataDictionary ViewData => _html.ViewData;
              public IServiceProvider provider => _html.ViewContext.HttpContext.RequestServices;



              1. after that I have created an extension method for IHtmlHelper

              public static class MyBuilderExtension

              public static MyBuilder Nubess(this IHtmlHelper html)

              return new MyBuilder(new MyHtmlHelperAdapter(html));




              where MyBuilder is



              public class MyBuilder

              private readonly MyHtmlHelperAdapter _htmlHelper;

              public MyBuilder(MyHtmlHelperAdapter htmlHelper)

              _htmlHelper = htmlHelper;


              public FormBuilder<object> Form<T>(IDictionary<string, string> customizeArgs = null, FormBuilder<object> externalForm = null)

              return new FormBuilder(_htmlHelper, typeof(T), customizeArgs, externalForm).Build();




              1. now I can create my custom contents for views using class thanks to MyHtmlHelperAdapter

               public class FormBuilder

              private MyHtmlHelperAdapter _htmlHelper;
              private readonly IStringLocalizer<SharedResources> _localizer;
              private readonly LinkGenerator _linkGenerator;
              private readonly IEngine _engine;
              private readonly IEngineElement _element;
              private readonly Type _typeDescriptor;
              private readonly IDictionary<string, string> _descriptorArgs;

              /* variabili per semplificare la gestione del builder */
              private readonly FormBuilder<object> Form;
              private readonly FormConfig Config;
              private readonly IList<FormGroupConfig> Groups;
              private readonly IList<FormItemConfig> Items;
              private readonly IDictionary<string, string> FormOptions;

              private readonly string _clientPrefix = "smtForm_0_";

              public FormBuilder(MyHtmlHelperAdapter htmlHelper, Type typeDescriptor, IDictionary<string, string> ModelCustomizeArgs = null, FormBuilder<object> externalForm = null)

              _htmlHelper = htmlHelper;
              _localizer = _htmlHelper.provider.GetRequiredService<IStringLocalizer<SharedResources>>() ?? throw new ArgumentNullException();
              _linkGenerator = _htmlHelper.provider.GetRequiredService<LinkGenerator>() ?? throw new ArgumentNullException();
              _engine = _htmlHelper.provider.GetRequiredService<IEngine>() ?? throw new ArgumentNullException();

              //code..



              public FormBuilder<object> Build()

              //code..
              return Form;


              //methods..






              share|improve this answer



























                1














                I thank Itminus for answering me.



                However call IHtmlHelper on controller constructor it is not enough, you must contextualize IHtmlHelper before using it.



                I want to share another solution that I found and solve my problem, maybe It can be useful for other users.
                Please see https://gist.github.com/Blackleones/eb0d02b9dd99164271af88e22143d72b#file-example-cs to remember what my goal is.



                1. To solve my problem I have created a class called HtmlHelperAdapter that contains some instances I need.

                public class MyHtmlHelperAdapter

                public IHtmlHelper _html;

                public NubessHtmlHelperAdapter(IHtmlHelper html)

                _html = html;


                public IHtmlHelper Html => _html;
                public ViewContext ViewContext => _html.ViewContext;
                public HttpContext HttpContext => _html.ViewContext.HttpContext;
                public ViewDataDictionary ViewData => _html.ViewData;
                public IServiceProvider provider => _html.ViewContext.HttpContext.RequestServices;



                1. after that I have created an extension method for IHtmlHelper

                public static class MyBuilderExtension

                public static MyBuilder Nubess(this IHtmlHelper html)

                return new MyBuilder(new MyHtmlHelperAdapter(html));




                where MyBuilder is



                public class MyBuilder

                private readonly MyHtmlHelperAdapter _htmlHelper;

                public MyBuilder(MyHtmlHelperAdapter htmlHelper)

                _htmlHelper = htmlHelper;


                public FormBuilder<object> Form<T>(IDictionary<string, string> customizeArgs = null, FormBuilder<object> externalForm = null)

                return new FormBuilder(_htmlHelper, typeof(T), customizeArgs, externalForm).Build();




                1. now I can create my custom contents for views using class thanks to MyHtmlHelperAdapter

                 public class FormBuilder

                private MyHtmlHelperAdapter _htmlHelper;
                private readonly IStringLocalizer<SharedResources> _localizer;
                private readonly LinkGenerator _linkGenerator;
                private readonly IEngine _engine;
                private readonly IEngineElement _element;
                private readonly Type _typeDescriptor;
                private readonly IDictionary<string, string> _descriptorArgs;

                /* variabili per semplificare la gestione del builder */
                private readonly FormBuilder<object> Form;
                private readonly FormConfig Config;
                private readonly IList<FormGroupConfig> Groups;
                private readonly IList<FormItemConfig> Items;
                private readonly IDictionary<string, string> FormOptions;

                private readonly string _clientPrefix = "smtForm_0_";

                public FormBuilder(MyHtmlHelperAdapter htmlHelper, Type typeDescriptor, IDictionary<string, string> ModelCustomizeArgs = null, FormBuilder<object> externalForm = null)

                _htmlHelper = htmlHelper;
                _localizer = _htmlHelper.provider.GetRequiredService<IStringLocalizer<SharedResources>>() ?? throw new ArgumentNullException();
                _linkGenerator = _htmlHelper.provider.GetRequiredService<LinkGenerator>() ?? throw new ArgumentNullException();
                _engine = _htmlHelper.provider.GetRequiredService<IEngine>() ?? throw new ArgumentNullException();

                //code..



                public FormBuilder<object> Build()

                //code..
                return Form;


                //methods..






                share|improve this answer

























                  1












                  1








                  1







                  I thank Itminus for answering me.



                  However call IHtmlHelper on controller constructor it is not enough, you must contextualize IHtmlHelper before using it.



                  I want to share another solution that I found and solve my problem, maybe It can be useful for other users.
                  Please see https://gist.github.com/Blackleones/eb0d02b9dd99164271af88e22143d72b#file-example-cs to remember what my goal is.



                  1. To solve my problem I have created a class called HtmlHelperAdapter that contains some instances I need.

                  public class MyHtmlHelperAdapter

                  public IHtmlHelper _html;

                  public NubessHtmlHelperAdapter(IHtmlHelper html)

                  _html = html;


                  public IHtmlHelper Html => _html;
                  public ViewContext ViewContext => _html.ViewContext;
                  public HttpContext HttpContext => _html.ViewContext.HttpContext;
                  public ViewDataDictionary ViewData => _html.ViewData;
                  public IServiceProvider provider => _html.ViewContext.HttpContext.RequestServices;



                  1. after that I have created an extension method for IHtmlHelper

                  public static class MyBuilderExtension

                  public static MyBuilder Nubess(this IHtmlHelper html)

                  return new MyBuilder(new MyHtmlHelperAdapter(html));




                  where MyBuilder is



                  public class MyBuilder

                  private readonly MyHtmlHelperAdapter _htmlHelper;

                  public MyBuilder(MyHtmlHelperAdapter htmlHelper)

                  _htmlHelper = htmlHelper;


                  public FormBuilder<object> Form<T>(IDictionary<string, string> customizeArgs = null, FormBuilder<object> externalForm = null)

                  return new FormBuilder(_htmlHelper, typeof(T), customizeArgs, externalForm).Build();




                  1. now I can create my custom contents for views using class thanks to MyHtmlHelperAdapter

                   public class FormBuilder

                  private MyHtmlHelperAdapter _htmlHelper;
                  private readonly IStringLocalizer<SharedResources> _localizer;
                  private readonly LinkGenerator _linkGenerator;
                  private readonly IEngine _engine;
                  private readonly IEngineElement _element;
                  private readonly Type _typeDescriptor;
                  private readonly IDictionary<string, string> _descriptorArgs;

                  /* variabili per semplificare la gestione del builder */
                  private readonly FormBuilder<object> Form;
                  private readonly FormConfig Config;
                  private readonly IList<FormGroupConfig> Groups;
                  private readonly IList<FormItemConfig> Items;
                  private readonly IDictionary<string, string> FormOptions;

                  private readonly string _clientPrefix = "smtForm_0_";

                  public FormBuilder(MyHtmlHelperAdapter htmlHelper, Type typeDescriptor, IDictionary<string, string> ModelCustomizeArgs = null, FormBuilder<object> externalForm = null)

                  _htmlHelper = htmlHelper;
                  _localizer = _htmlHelper.provider.GetRequiredService<IStringLocalizer<SharedResources>>() ?? throw new ArgumentNullException();
                  _linkGenerator = _htmlHelper.provider.GetRequiredService<LinkGenerator>() ?? throw new ArgumentNullException();
                  _engine = _htmlHelper.provider.GetRequiredService<IEngine>() ?? throw new ArgumentNullException();

                  //code..



                  public FormBuilder<object> Build()

                  //code..
                  return Form;


                  //methods..






                  share|improve this answer













                  I thank Itminus for answering me.



                  However call IHtmlHelper on controller constructor it is not enough, you must contextualize IHtmlHelper before using it.



                  I want to share another solution that I found and solve my problem, maybe It can be useful for other users.
                  Please see https://gist.github.com/Blackleones/eb0d02b9dd99164271af88e22143d72b#file-example-cs to remember what my goal is.



                  1. To solve my problem I have created a class called HtmlHelperAdapter that contains some instances I need.

                  public class MyHtmlHelperAdapter

                  public IHtmlHelper _html;

                  public NubessHtmlHelperAdapter(IHtmlHelper html)

                  _html = html;


                  public IHtmlHelper Html => _html;
                  public ViewContext ViewContext => _html.ViewContext;
                  public HttpContext HttpContext => _html.ViewContext.HttpContext;
                  public ViewDataDictionary ViewData => _html.ViewData;
                  public IServiceProvider provider => _html.ViewContext.HttpContext.RequestServices;



                  1. after that I have created an extension method for IHtmlHelper

                  public static class MyBuilderExtension

                  public static MyBuilder Nubess(this IHtmlHelper html)

                  return new MyBuilder(new MyHtmlHelperAdapter(html));




                  where MyBuilder is



                  public class MyBuilder

                  private readonly MyHtmlHelperAdapter _htmlHelper;

                  public MyBuilder(MyHtmlHelperAdapter htmlHelper)

                  _htmlHelper = htmlHelper;


                  public FormBuilder<object> Form<T>(IDictionary<string, string> customizeArgs = null, FormBuilder<object> externalForm = null)

                  return new FormBuilder(_htmlHelper, typeof(T), customizeArgs, externalForm).Build();




                  1. now I can create my custom contents for views using class thanks to MyHtmlHelperAdapter

                   public class FormBuilder

                  private MyHtmlHelperAdapter _htmlHelper;
                  private readonly IStringLocalizer<SharedResources> _localizer;
                  private readonly LinkGenerator _linkGenerator;
                  private readonly IEngine _engine;
                  private readonly IEngineElement _element;
                  private readonly Type _typeDescriptor;
                  private readonly IDictionary<string, string> _descriptorArgs;

                  /* variabili per semplificare la gestione del builder */
                  private readonly FormBuilder<object> Form;
                  private readonly FormConfig Config;
                  private readonly IList<FormGroupConfig> Groups;
                  private readonly IList<FormItemConfig> Items;
                  private readonly IDictionary<string, string> FormOptions;

                  private readonly string _clientPrefix = "smtForm_0_";

                  public FormBuilder(MyHtmlHelperAdapter htmlHelper, Type typeDescriptor, IDictionary<string, string> ModelCustomizeArgs = null, FormBuilder<object> externalForm = null)

                  _htmlHelper = htmlHelper;
                  _localizer = _htmlHelper.provider.GetRequiredService<IStringLocalizer<SharedResources>>() ?? throw new ArgumentNullException();
                  _linkGenerator = _htmlHelper.provider.GetRequiredService<LinkGenerator>() ?? throw new ArgumentNullException();
                  _engine = _htmlHelper.provider.GetRequiredService<IEngine>() ?? throw new ArgumentNullException();

                  //code..



                  public FormBuilder<object> Build()

                  //code..
                  return Form;


                  //methods..







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 11 at 16:53









                  Leonardo LurciLeonardo Lurci

                  407




                  407



























                      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%2f55067308%2fusing-ihtmlhelper-with-dependency-injection%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

                      Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                      Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                      Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved