简体   繁体   中英

Implicit interface based on class

I have a lot of classes in my business layer that have an interface which must always have the same methods and properties as the public methods and properties of my business class. This is a common scenario, as the interface is needed for dependency injection and mocking while unit testing.

It would be optimal if I could somehow define the interface as the same as the public methods and properties of a class. That way I don't have to copy paste method definitions from my implemented class to my interface all the time. I don't see any logical problem with this, but I know that it's not directly possible to do in C#.

Perhaps someone can come up with a reasonable way to accomplish this?

Here is an example. Here is an interface.

public interface IAccountBusiness
{
    Guid GetAccountIdByDomain(string domain);

    void CreateAccount(string accountType, string accountName);
}

Here is the implementation:

public class AccountBusiness : IAccountBusiness
{
    public Guid GetAccountIdByDomain(string domain)
    {
        // Implementation
    }

    public void CreateAccount(string accountType, string accountName)
    { 
        // Implementation
    }
}

If I want to add a parameter more in CreateAccount, for example "Email", then I have to add it to both the interface and the business class. In this example it's a minor nuisance but in larger scale projects it's ... well ... still a minor nuisance, but it doesn't have to be.

Resharper's Change Signature refactoring allows you to do that easily:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM