Windows service load dll

Load dll and host it as windows service

I have 3 Restful services which I want to host as windows service. I have created one installer which will host all three services together. I want to make my installer a bit configurable. I want to add new services to the same installer without needing it to edit the code.

Here is my current code for the installer. Here I am giving reference to the dll and hosting them. This is just normal code for any windows host project.

Code in the installer.

What I have tried is here. I removed the service endpoint configuration from app.config and did it in code. I put all the dlls in one folder and loading those dlls in code. To get the service and interface I am adding parameters in the app.config as follows which will give the service name and interface name to retrieve from loaded assembly. It all works fine. But I have a little problem, I have explained below.

New App.config file

New Windows host code

What I am doing here is creating an instance of the loaded dll and hosting it as a windows service.

This works fine if your service behaviour have InstanceContextMode set to single. Else it gives an error.

Error: «Service cannot be started. System.InvalidOperationException: In order to use one of the ServiceHost constructors that takes a service instance, the InstanceContextMode of the service must be set to InstanceContextMode.Single. This can be configured via the ServiceBehaviorAttribute. Otherwise, please consider using the ServiceHost constructors that take a Type argument.»

I tried modifying the code like this

But it does not work. Please help. Is there any other way to achieve this.

How to run a dll as a service?

I know how to write a dll and how to write a service and how to run a dll with rundll32 , but now I want to write a dll that install as a service in windows

I don’t know if that’s possible or which function in dll should be exported?

How can I install and run a dll as a service?

2 Answers 2

There are a few different ways to run a DLL as a service. You can either:

Write your own .exe service and have it load your DLL as needed. This is the recommended approach.

Use Microsoft’s SVCHOST.EXE to host your DLL. Have your DLL export a ServiceMain() function, add a ServiceDLL value to your service’s Registry key to point at your DLL, add your service name to a new group in SVCHOST’s Registry key, and then set svchost -k as the executable for your service. See these articles for more details:

Читайте также:  Просмотр автозапуска windows 10

Note, however, that MSDN’s Service Programs documentation warns against this approach:

A service program created with the type SERVICE_WIN32_SHARE_PROCESS contains code for more than one service, enabling them to share code. An example of a service program that does this is the generic service host process, Svchost.exe, which hosts internal Windows services. Note that Svchost.exe is reserved for use by the operating system and should not be used by non-Windows services. Instead, developers should implement their own service hosting programs.

Write your service as a kernel-mode driver that exports a DriverEntry() function, and add a ServiceDLL value in your service’s Registry key pointing at the DLL file. See this article for more details:

I would not recommend this approach, unless you are designing your own hardware.

Как исправить ошибки DLL файлов в Windows 10, 8 или 7

Читайте, как восстановить сбойные DLL библиотеки в Windows 10, 8 или 7 . Какие причины повреждения, удаления или ошибок DLL файлов. Сами по себе DLL файлы не являются исполняемыми файлами, но они используются в работе другими программами. Часто несколько программ или драйверов могут использовать DLL файл совместно, поэтому удаление или обновление одной программы может вывести из строя другие.

Если вы получаете сообщения: «DLL файл не найден или отсутствует» , «не удалось зарегистрировать DLL библиотеку» , «отсутствует необходимый компонент» или «необходима повторная установка приложения» , то наша инструкция будет полезна для вас. Такие сообщения могут возникать во время запуска любого приложения или игры, во время установки, обновления или старта системы Windows 10, 8 или 7.

Для выявления причины ошибки и получения рекомендаций по её устранению можно использовать Журнал событий системы. Особенно полезно это будет если ошибка блокирует загрузку системы или вызывает синий экран смерти (BSOD) .

Если вы не можете запустить систему из-за ошибки в обычном режиме, используйте загрузку в безопасном режиме .

Возможные причины повреждения, удаления или ошибок DLL файлов

  • Непреднамеренное удаление DLL файлов по ошибке.
  • Перезапись системных DLL файлов устаревшими версиями.
  • Заражение вирусами или вредоносным ПО.
  • Повреждение жесткого диска.
  • Отсутствие или повреждение драйверов оборудования.
  • В Windows находятся несовместимые версии файлов, которые принадлежат к различным приложениям.
  • Отсутствие необходимых компонентов Windows: DirectX, C++ Runtime Library, .NET Framework.
  • Автоматические обновления Windows и драйверов системы.
  • Использование устаревших или не правильных драйверов.
  • Повреждение или удаление критически важных веток реестра.

Способы восстановления DLL файлов в Windows 10

  • Если Windows перестала загружаться, или были повреждены или удалены системные файлы, вы можете воспользоваться инструментами среды восстановления.
  • Так же в Windows 10, 8 или 7 присутствует инструмент для автоматического восстановления системных файлов или библиотек из командной строки.
  • Ошибки, связанные c отсутствием необходимых библиотек DirectX или C++ Runtime Library являются наиболее часто встречаемыми проблемами в Windows.
Читайте также:  Asus k73tk драйвера windows 10

Вам необходимо установить совместимую версию DirectX, если игра вылетает с ошибкой: “Запуск программы не возможен, так как на компьютере отсутствует файл DLL. Попробуйте переустановить программу” , или в тексте ошибки указаны следующие библитеки: d3dx9_43.dll, xinput1_3.dll, d3dx9_31.dll, d3dx9_34.dll, xinput1_2.dll, d3d11.dll, d3dx9_35.dll, dxgi.dll, d3dx9_25.dll, d3d11.dll, d3dx9.dll, d3dx9_43.dll, d3dx10_43.dll, d3dx9_26.dll, d3dx9_30.dll, d3dx9_27.dll, d3dx11_43.dll, d3dcompiler_43.dll, d3d10.dll, xinput1_3.dll, d3dx9_31.dll, xinput1_2.dll, d3dx9_31.dll, d3dx9_34.dll, d3dx9_42.dll, x3daudio1_7.dll, x3daudio1_6.dll, xrsound.dll . Для этого необходимо воспользоваться Web инсталлятором DirectX от Microsoft .
Установите необходимую версию C++ Runtime Library, если в тексте ошибки указаны библитеки содержащие слова MSVCR или RUNTIME: MSVCR120.dll, MSVCP120.dll, MSVCR110.dll, MSVCP110.dll, MSVCR100.dll, MSVCP100.dll, MSVCR90.dll, MSVCP90.dll, MSVCR80.dll, MSVCP80.dll, VCRUNTIME140.dll, runtime-x64.dll, runtime-x32.dll, runtime.dll, runtime-110.dll и т.д.
Найдите в системных требованиях к программе какая версия библиотек C++ Runtime Dll необходима для работы и установите нужную:

Переустановите программу, ссылающуюся на DLL файл. Причиной ошибки DLL файла может быть ошибка в работе использующей его программы.

Windows service dll search path

I have developed a windows service using .net . My service makes some calls to unmanaged code like follows —

I have placed cmxConnect.dll within the same folder as the service executable. The service starts fine if I set the logon user to be my domain account. But if I start the service using the local system account I get DLL not found exceptions. I am guessing there is something in my environment settings thats enables windows to find cmxConnect.dll. Can someone point out what exactly this is?

4 Answers 4

The Local System account is pretty powerful. It’s possible that the DLL search order is disabled for this account for security. (If it goes searching just by name, and somebody manages to put a malicious DLL somewhere in the search order, then you’ve got an escalation of privilege vulnerability.) If it’s a .NET service, you probably want to add your DLL to your manifest and get your DLL installed in the GAC. (I’m not a .NET guy. I’ve just heard these terms before.)

Try process monitor from msft. This tool will show you where the service is looking for your dll. It may even be looking for a dependant dll. This would also show up in process monitor.

I’m guessing here, but have you checked the Environment Variables. Does your local system a/c have the same set of Env. Vars?

As I understand things the DllImport attribute simply wraps a call to LoadLibrary, so the standard Dynamic Link Library Search Order should apply.

Читайте также:  Активатор для windows 7600 x64

Services will run in a far more restricted environment that user code — I can see that it would be undesirable to load dlls from any location other than the exe’s folder and System32 — everywhere else opens one up to a pre-loading attack, and that would be pretty serious with a service.

It could be that simple: Services can only search for dlls from System32?

The trusted locations to find dlls are:

  1. When passed an explicit path its clear to LoadLibrary that the app knows which dll it wants. Can you pass a fully qualified path to DllImport?
  2. The most trusted non-fully qualified place to search for dlls is in WinSxS — if you build the dll yourself, perhaps deploying it as a native Side by side assembly is an option.
  3. The exe’s own folder. Usually. I can’t imagine that because the service is a .net app that this wouldn’t apply. But clearly there is an issue here.
  4. System32 — you might need to install it here.

Windows Service can’t load DLLs on release

This is a little weird and I’ve been racking my brain for the past week trying to figure this out.

I have a windows service that’s going to serve as a new site launcher (internal tool). I have 5 projects in the solution:

  • IISWrapper (.NET Standard 2.0)
  • SiteLauncher (this is the service project) (.NET Framework 4.7)
  • SiteLauncher.Debug (console app for debugging web interface) (.NET Framework 4.7)
  • SiteLauncher.Actions (.NET Framework 4.7)
  • SiteLauncher.WebUI (.NET Framework 4.7)

I’m using NancyFx self hosting as the web interface. All 5 projects are built with the x86 architecture set in Visual Studio. IISWrapper references Micorosft.Web.Administration, which is .NET Core, so it has to be .NET Standard for the service to use it.

This all works. As long as the service is built in debug. If I switch it to Release, I get errors like this when it tries to interact with IIS:

Could not load file or assembly ‘System.Diagnostics.TraceSource, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. The located assembly’s manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

NewSiteSetup.cs line 303 is the using statement:

The IISManager.CreateAppPool method:

I have verified that this library exists in the output folder. Oddly enough, I get this on the console app project in release as well. I don’t know what the difference is.

I’ve verified that the same packages are installed in the service and the console app. Both seem to work in debug mode but fail in release mode.

Оцените статью