views:

108

answers:

1

In asp.net MVC dependancy injection with controllers is simple and straightforward. Now, I'd like to remove most of the logic from views by using helpers. The problem is that these helpers use some of the objects that are injected.

Let me write an example:

public interface ISessionData
{
  List<string> IdList {get;}
}

public MyController : Controller
{

  public MyController(ISessionData sessionData)
  {
    ...
  }
}

session data is injected into controller. So far so good. But now I have a helper. Let's say it looks like this:

 public class MyHelper
    {
        private readonly ISessionData sessionData;

        public MyHelper(ISessionData sessionData)
        {
            this.sessionData = sessionData;
        }

        public bool CheckSomethingExistsInSession(string id)
        {
            return sessionData.IdList.Any(x => x.Id.Equals(id));
        }
}

Now what? I'd like MyHelper to be injected into view. Only way I can see is adding this helper to model and passing it to view every time. Any other ideas?

+2  A: 

In MVC it is better to pass ISessionData data from Controller to View (using ViewModel or ViewData):

ViewData["Session"] = sessionData.IdList.ToList();

And remove ISessionData dependency from the helper. Something like this:

public class MyHelper
{
    //private readonly ISessionData sessionData;

    public MyHelper(/*ISessionData sessionData*/)
    {
        //this.sessionData = sessionData;
    }

    public bool CheckSomethingExistsInSession(string id, IList<...> sessionData)
    {
        return sessionData.Any(x => x.Id.Equals(id));
    }
}

In View:

<% var somethingExists = new MyHelper().CheckSomethingExistsInSession(
    1, ViewData["Session"] as IList<...>); %>

UPDATED:

public static class MyHelper
{
    public static bool CheckSomethingExistsInSession(string id, IList<...> sessionData)
    {
        return sessionData.Any(x => x.Id.Equals(id));
    }
}

<% var somethingExists = MyHelper.CheckSomethingExistsInSession(
    1, ViewData["Session"] as IList<...>); %>
eu-ge-ne