IoC with Web Service

2

I need to create a WS with IoC.

  • I created a new Web project with Web API dependencies;
  • I've added a Web Service (asmx);
  • I installed SimpleInjector;
  • The code looks like this:

        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
    
        public class WSI : System.Web.Services.WebService
        {
    
                private readonly ICrypto _crypto;
    
                public WSI(ICrypto crypto)
                {
                    _crypto = crypto;
                }
    
                [WebMethod]
                public string HelloWorld()
                {
                    return _crypto.Encrypt("Hello World");
                }
        }
    

    The SimpleInjector startup file looks like this:

     public static void Initialize()
        {
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
    
            InitializeContainer(container);
    
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
    
            container.Verify();
    
            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
        }
    
        private static void InitializeContainer(Container container)
        {
            container.Register<ICrypto, Crypto>();
        }
    

    When I run I get the error:

    System.MissingMethodException: Nenhum construtor sem par&#226;metros foi definido para este objeto.
    em System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
    em System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
    em System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
    em System.Activator.CreateInstance(Type type, Boolean nonPublic)
    em System.Activator.CreateInstance(Type type)
    em System.Web.Services.Protocols.ServerProtocol.CreateServerInstance()
    em System.Web.Services.Protocols.WebServiceHandler.Invoke()
    em System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
    
        
    asked by anonymous 20.01.2017 / 11:48

    1 answer

    2

    If you understand your problem, it must be because WebService (asmx) does not allow them to have constructors, because its implementation is via proxy (which is added as reference to the Service in the client) that is replaced.

    If it is really necessary to use SimpleInjector I recommend changing the approach to WCF.

    More information: CodeProject

    I hope I have helped in some way. ;)

        
    20.01.2017 / 13:03