1
votes

I have an asp.net mvc application and need to call wcf service in it. I've added service reference to the project. I use unity for dependency injection and want to inject wcf client. But it's not so simple because of System.ServiceModel.ClientBase. I did it this way.
This is an autogenerated proxy:

public partial class WcfServiceClient : 
    System.ServiceModel.ClientBase<WcfUnity.IWcfServiceClient>, 
    WcfUnity.IWcfServiceClient 
{
    //autogenerated constructors and methods
}

I created interface:

public interface ISimpleProxy : WcfUnity.IWcfServiceClient
{
    //duplication of methods' signatures
    void CloseConnection();
}

I extended WcfServiceClient using partial class:

public partial class WcfServiceClient : ISimpleProxy
{
    public void CloseConnection()
    {
        try
        {
            Close();
        }
        catch (Exception)
        {
            Abort();
        }
    }
}

And inject it like this:

container.RegisterType<ISimpleProxy>(new InjectionFactory(c => new WcfServiceClient()));

So I don't have dependecies from ClientBase and there is no wcf stuff inside classes which use this wcf proxy. Does this solution have some disadvatages?

1
This solution is BAD. It is the responsibility of IOC to handle scope for you. ClientBase already implements IDisposable, so everything should be working fine without any work. Your code should only know about ISimpleProxy and you should let Unity handle WcfServiceClient logic. - Aron
@Aron, so do I need to delete CloseConnection() and use ISimpleProxy methods only? - mtkachenko
My bad. What I mean is that ISimpleProxy should not exist. You should just have IWcfServiceClient in your code. You should register using container.RegisterType<WcfServiceClient, IWcfServiceClient>(lifetimeManager);. Then get rid of everything else. - Aron

1 Answers

1
votes

No, it doesn't, I use (mostly) the same approach.

I would recommend you making your interface inherit from IDisposable, because underlying ClientBase<T> is disposable. This way you won't need CloseConnection.