2

I have an asp.net WebForm project, and i want to split up the logic in several projects:

I created 3 projects in the solution. -Frontend -Contract & -Backend

Contract consists of Models and a Contract Interface. Backend implements the Interface from Contract.

Is it possible from frontend to call the methods in Contract, without knowing the backend where the Interface are implemented?

user1501050
  • 105
  • 1
  • 8
  • 3
    Yes, it's possible (dependency injection). – Michael Liu Oct 29 '13 at 15:09
  • 1
    do you mean you want to load one of different backends dynamically? If so you can take a look at http://stackoverflow.com/questions/515925/system-with-plugins-in-c-sharp – Paolo Falabella Oct 29 '13 at 15:13
  • 2
    Absolutely it is. In fact, this is a key usage of interfaces: it allows you to uncouple the caller from the callee. So good on you for wanting to do this: you have just "levelled up" as a developer! ;) – David Arno Oct 29 '13 at 15:17
  • 2
    See http://en.wikipedia.org/wiki/Dependency_injection – Rui Jarimba Oct 29 '13 at 15:22

1 Answers1

6

You mean like this?

public interface IContract { void Method(); }

public class Backend : IContract { public void Method() {} }

public class Frontend
{
    public IContract Contract { get; set; }

    public Frontend(IContract contract)
    {
        Contract = contract;
    }

    public void DoSomething()
    {
        Contract.Method();
    }
}

In your initialiser for Frontend you could either pass in new Backend() explicitly, or use a Dependency Injection framework to have the IContract interface parameter automatically resolved from defined configuration.

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
Matt Mitchell
  • 40,943
  • 35
  • 118
  • 185
  • Thx for helping out. Is it "wrong" to explicitly pass in: new Backend(), when the object is initialised in frontend? Because then the frontend have a reference to Backend? – user1501050 Oct 30 '13 at 09:20
  • Good question. I don't think so, if you define your front-end as the overarching application itself / the "controller" if you like. That doesn't mean you should be accessing methods on the Backend instance that aren't part of IContract though. The other option is to be using DI such as Ninject, Autofac, StructureMap, Unity or others which would have a setup class or config file, and then you'd make a .Resolve() call (or something similar) that would instantiate the Backend. At the end of the day it's going to be defined somewhere though. – Matt Mitchell Oct 30 '13 at 12:39
  • By having it passed in as a parameter, you're at least making it easy to switch out for testing (i.e. your test could make a new Frontend using a MockBackend object). – Matt Mitchell Oct 30 '13 at 12:39
  • 1
    Thx for clarifying. I'll reference Backend in Frontend to start with. I think I'll look into some DI Frameworks as well. – user1501050 Oct 30 '13 at 13:08