How can I decouple my application from my membership service?

最后都变了- 提交于 2019-12-06 15:43:34

You already defined IMembershipService

public interface IMembershipService
{
    User GetCurrentUser( string userName );
}

Now change your FooController

public class FooController : Controller
{
    private readonly IMembershipService MembershipService;

    public FooController( IMembershipService membershipService )
    {
        MembershipService = membershipService;
    }

    [Authorize( Roles = "Administrator" )]
    public ActionResult DoSomething()
    {
        var user = MembershipService.GetUser( User.Identity.Name );

        // etc...
    }
}

Go and change everywhere in your code MembershipService to IMembershipService as shown in FooController. Now, register IMembershipService in Castle

container.Register( Component.For( typeof(IMembershipService) )
         .ImplementedBy( typeof(MembershipService) ) );

Now change Unit Tests

private Mock<IMembershipService> membershipServiceMock;

[TestInitialize]
public void MyTestInitialize()
{
    membershipServiceMock = new Mock<IMembershipService>();
}

[TestMethod]
public void DoSomethingReturnsWhatever()
{
    var controller = new FooController( membershipServiceMock.Object );

    // etc...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!