1

What's the best way of passing context to a custom business/helper class from an action method? The helper/business class that i'm creating will need information such as the currently logged in user, an instance of a UrlHelper class (to generate urls) and any other data that's related to ASP.NET MVC's infrastructure.

I was thinking of just passing the instance of a controller. Is this advisable? What's the best practice?

2 Answers 2

5

The helper/business class that i'm creating will need information such as the currently logged in user.

Unlikely. IMHO It will suffice the username => User.Identity.Name, which could be passed as a string parameter to this business tier.

an instance of a UrlHelper class (to generate urls)

Unlikely. Generating urls is not the responsibility of the business tier. Pass the urls directly from the controller which has an Url property allowing you to generate urls at free will (again as string parameters).

Conclusion: decouple your business logic from your infrastructure. Basically if you are calling something a business logic the sole notion of URL helper hardly makes sense. Once you cross the boundaries of the web tier there are no more url helpers.

Sign up to request clarification or add additional context in comments.

4 Comments

I like your answer. What if my class is a helper class that contains mostly application/UI logic that communicates to a web service that contains the business logic. Is it then okay for the helper class to be coupled with ASP.NET MVC's infrastructure?
@burnt1ce, yes, if it is a helper class (HtmlHelper, UrlHelper, ...) it is perfectly fine to be coupled with the ASP.NET MVC infrastructure and pass the required information to the business layer.
Thanks for the quick reply. Can I do the same with view models? For some of my view models, i would like to pass in the controller context and business entity to the constructor of the view model.
@burnt1ce, I wouldn't do this with view models. I would use a mapping layer and prepare everything in advance so that the view models already have the right form for the view.
1

To reduce coupling pass value types or parameter/dto classes that already exist in your business helper layer.

Don't pass anything related to the Web/UI tier.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.