daustinash
daustinash

Reputation: 504

Force .NET MVC Controller to Call Service Methods Rather Than Directly Calling Base Class

I have a standard class stack in a .NET MVC5 using Entity Framework 6:

MyController()
MyService() : ServiceBase()
ServiceBase() : IServiceBase

All methods/classes are public at the moment.

ServiceBase() contains generic(T) methods and is inherited by all services.

The problem is that MyController() can call the generic methods in ServiceBase() directly. Important properties need to be set on the Entity before being passed to ServiceBase().

Is there any way to hide the ServiceBase() methods from MyController() forcing MyController() to go through MyService() rather than calling ServiceBase() methods directly?

Thanks all.

Upvotes: 1

Views: 738

Answers (2)

daustinash
daustinash

Reputation: 504

The answer is to make the base classes that I don't want the controllers to access directly abstract while continuing to contain method implementation.

Make the ServiceBase classes abstract with a protected constructor. Then only classes that derive from them can access their methods directly, forcing the controller to call the controllers service which then calls the base service classes.

I wrote all this up in a blog post here

Upvotes: 0

Dan Csharpster
Dan Csharpster

Reputation: 2732

Why are you starting from an interface? I think you are getting your OO a little confused. I think the problem you are having is that you start at an interface, which doesn't have method visiblity controls. So you try to hide it in ServiceBase, but MyService has to know about the interface so that is why you cannot change visibility midway through.

I would suggest you rethink your OO strategy a bit.

However, if you really want to keep the interface and hide the methods in the base class, you can blank them out in MyService and inside of another method of MyService you can directly call the base class. I have created an example here.

But like I said, I would discourage this behavior and come up with a better OO strategy. If you can get around to posting your code, perhaps in a separate question, then I and the rest of the community can help you out with that. FYI, this might go better in the codereview stackexchange site.

Upvotes: 1

Related Questions