Autofac + WCF REST 4.0

旧城冷巷雨未停 提交于 2019-12-11 06:51:30

问题


I am building a WCF 4.0 REST service and want to use Autofac as DI container. Apparently, I want to be able to call a parameterized constructor of the service class (service contract implementation), which accepts a bunch of interfaces to work with. Those interfaces are to be registered within Autofac container and I want them resolved and used when creating an instance of my service class (instead of calling not parameterized constructor, which is default).

There is similar problem with MVC controllers, which is solved by Autofac MVC Integration package. Is there anything ready-to-use for WCF REST 4.0? If no, what is the best way to solve my problem? E.g., is there anything like MVC's DependencyResolver which I can set up to use Autofac?

Note, that since 4.0 they changed some concepts in WCF REST. E.g., now there is no .svc file, routing is enough to call required method. I am quite new to WCF REST 4.0, so I wanted to ask community for suggestions before spending days on implementing some huge custom mechanism. Alas, quick search over internet did not provide me with an acceptable solution.


回答1:


In your global application startup:

//Build a container with your service registered.
var builder = new ContainerBuilder();
builder.RegisterType<YourService>();
var container = builder.Build();

//Set AutofacHostFactory.Container with this built container.
AutofacHostFactory.Container = container;

//Use AutofacWebServiceHostFactory instead of WebServiceHostFactory
var factory = new AutofacWebServiceHostFactory();

//Add your routes
RouteTable.Routes.Add(new ServiceRoute("YourServiceUrl", factory, typeof(YourService)));

That's all.




回答2:


Have you looked at the existing WCF integration support?



来源:https://stackoverflow.com/questions/6680500/autofac-wcf-rest-4-0

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