user1501050
user1501050

Reputation: 105

Call Interface method, without knowing who implements the Interface?

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?

Upvotes: 2

Views: 277

Answers (1)

Matt Mitchell
Matt Mitchell

Reputation: 41871

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.

Upvotes: 6

Related Questions