MEF Import Exception w/ Visual Studio 2015 Extension - visual-studio

Hoping someone can provide me with some guidance on an issue I'm facing using MEF with my VS2015 extension. I'm attempting to extend the IntelliSense capabilities of VS and followed this tutorial as a basis: https://msdn.microsoft.com/en-us/library/ee372314.aspx
Here is my ICompletionSourceProvider:
[Export(typeof(ICompletionSourceProvider))]
[Name("Test Statement Completion Provider")]
[Order(Before = "default")]
[ContentType("text")]
internal class MyCompletionSourceProvider : ICompletionSourceProvider
{
[Import]
internal ITextStructureNavigatorSelectorService NavigatorService { get; set; }
[Import]
internal IServiceProvider ServiceProvider { get; set; }
public ICompletionSource TryCreateCompletionSource(ITextBuffer textBuffer)
{
return new MyCompletionSource(this, textBuffer);
}
}
The strange thing here is that this works fine on my machine (where this code was initially developed on), but fails to work on every other machine I've tried (both in Debug and Release). Breakpoints placed within TryCreateCompletionSource are never hit. I suspected this MEF component was never being exported, so I downloaded the mefx tool as recommend on MSDN and executed it on my generated DLL and received the following:
[Primary Rejection]
[Export] MyVSIX.Source.MyCompletionSourceProvider (ContractName="Microsoft.VisualStudio.Language.Intellisense.ICompletionSourceProvider")
[Import] MyVSIX.Source.MyCompletionSourceProvider.NavigatorService (ContractName="Microsoft.VisualStudio.Text.Operations.ITextStructureNavigatorSelectorService")
[Exception] System.ComponentModel.Composition.ImportCardinalityMismatchException: No exports were found that match the constraint:
ContractName Microsoft.VisualStudio.Text.Operations.ITextStructureNavigatorSelectorService
RequiredTypeIdentity Microsoft.VisualStudio.Text.Operations.ITextStructureNavigatorSelectorService
at System.ComponentModel.Composition.Hosting.ExportProvider.GetExports(ImportDefinition definition, AtomicComposition atomicComposition)
at Microsoft.ComponentModel.Composition.Diagnostics.CompositionInfo.AnalyzeImportDefinition(ExportProvider host, IEnumerable`1 availableParts, ImportDefinition id)
[Import] MyVSIX.Source.MyCompletionSourceProvider.ServiceProvider (ContractName="System.IServiceProvider")
[Exception] System.ComponentModel.Composition.ImportCardinalityMismatchException: No exports were found that match the constraint:
ContractName System.IServiceProvider
RequiredTypeIdentity System.IServiceProvider
at System.ComponentModel.Composition.Hosting.ExportProvider.GetExports(ImportDefinition definition, AtomicComposition atomicComposition)
at Microsoft.ComponentModel.Composition.Diagnostics.CompositionInfo.AnalyzeImportDefinition(ExportProvider host, IEnumerable`1 availableParts, ImportDefinition id)
If I remove the [Import] statements these are all resolved and things begin working again. From the tutorial though, this seems as though it should just work. This also doesn't explain why it works 100% of the time on my machine and never works on any other machines.
This is my .vsixmanifest file:
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Id="MyVSIX.Company.39048217-955a-4402-84e9-8a24f0730e72" Version="1.0" Language="en-US" Publisher="MyVSIX" />
<DisplayName>MyVSIX</DisplayName>
<Description xml:space="preserve"></Description>
<Icon>Resources\MyVSIX.ico</Icon>
</Metadata>
<Installation>
<InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[14.0]" />
</Installation>
<Dependencies>
<Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="[4.5,)" />
<Dependency Id="Microsoft.VisualStudio.MPF.14.0" DisplayName="Visual Studio MPF 14.0" d:Source="Installed" Version="[14.0]" />
</Dependencies>
<Assets>
<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" />
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" />
<Asset Type="Microsoft.VisualStudio.ItemTemplate" Path="Output\ItemTemplates" />
<Asset Type="Microsoft.VisualStudio.ProjectTemplate" Path="Output\ProjectTemplates" />
</Assets>
</PackageManifest>

Figured out why it wasn't working on other machines, but I still cannot understand why it was ever working on my machine. I changed this:
[Import]
internal IServiceProvider ServiceProvider { get; set; }
to this:
[Import(typeof(SVsServiceProvider)]
internal IServiceProvider ServiceProvider { get; set; }
Hope this helps someone in the future - I spent 2 days figuring this out!

Related

How to declare a element for complex data type defined in a xsd file located in jar file

I have a below xsd file in a jar dependency file in a Spring boot project. The xsd does not declare the element declaration, which is required by spring boot validation. So I am trying to add another xsd in my project resource folder to declare element type.
XSD in Jar file: /wsdl/xsd/UserService-v1-0.xsd
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema targetNamespace="http://usermanagement.com/userservice/xsd/2014/07"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:userservice="http://usermanagement.com/userservice/xsd/2014/07"
elementFormDefault="qualified">
<xsd:import namespace="http://usermanagement.com/userservice/common/xsd/2014/09" schemaLocation="userserviceCommon-v1-0.xsd"/>
<xsd:import namespace="http://usermanagement.com/userserviceabsolute/common/xsd/2014/09" schemaLocation="userserviceAbsoluteCommon-v1-0.xsd"/>
<xsd:complexType name="GetUsersRequest">
<xsd:attribute name="language" type="xsd:language" use="optional" default="en" />
</xsd:complexType>
</xsd:schema>
Please note that I tried to keep the complex type simple by removing some of the elements for this post. The location of file is /wsdl/xsd.
XSD to declare the element in the main Project resource: /wsdl/xsd/UserService-type-v1-0.xsd
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema targetNamespace="http://usermanagement.com/userservice/wsdl/userserviceService-v1-0"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:userservice="http://usermanagement.com/userservice/xsd/2014/07"
elementFormDefault="qualified">
<import namespace="http://usermanagement.com/userservice/xsd/2014/07" schemaLocation="jar:file://{path to the jar}/!/wsdl/xsd/userserviceService-v1-0.xsd"/>
<element name="GetUsersRequest" type="userservice:GetUsersRequest"/>
</xsd:schema>
As per my understanding we need to refer to the schemaLocation of xsd file in jar using notation "jar:file://{path to the jar}/!/wsdl/xsd/userserviceService-v1-0.xsd".
However I am not sure how to declare the path to the jar. Also not sure if this is the only way to refer to the definitions in the xsd in the jar files. In the above approach when ever a new version of jar is released we need to update the xsd file.
Also including the Spring WS schema validation config:
#Configuration
public class MyWsValidatorConfig extends WsConfigurerAdapter {
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
PayloadValidatingInterceptor validatingInterceptor = new PayloadValidatingInterceptor();
validatingInterceptor.setValidateRequest(true);
validatingInterceptor.setValidateResponse(true);
validatingInterceptor.setXsdSchemaCollection(new XsdSchemaCollection() {
#Override
public XsdSchema[] getXsdSchemas() {
return null;
}
#Override
public XmlValidator createValidator() {
try {
return XmlValidatorFactory.createValidator(getSchemas(), "http://www.w3.org/2001/XMLSchema");
} catch (Exception e) {
log.error("Failed to create validator e={}", e);
}
return null;
}
public Resource[] getSchemas() {
List<Resource> schemaResources = new ArrayList<>();
schemaResources.add(new ClassPathResource("/wsdl/xsd/UserService-v1-0.xsd"));
schemaResources.add(new ClassPathResource("/wsdl/xsd/UserService-type-v1-0.xsd"));
return schemaResources.toArray(new Resource[schemaResources.size()]);
}
});
interceptors.add(validatingInterceptor);
}
}
This is the first time I am working with XSD and SOAP web services. Able to cross other hurdles but got stuck with this issue.
Please help.

Mybatis - Invalid bound statement (not found)

I have created a new project using mybatis to connect to a mysql database. This is my second project using mybatis so I am familiar with it but am getting the following error when I call the save method:
2019-03-05 10:08:01.031 ERROR 86438 --- [nio-9905-exec-1] c.q.f.r.c.ResolveRestController : Error starting preset: Invalid bound statement (not found): com.qlsdistribution.fps.resolverender.data.mybatis.mapper.ResolveJobReportMapper.saveResolveJobReport
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.qlsdistribution.fps.resolverender.data.mybatis.mapper.ResolveJobReportMapper.saveResolveJobReport
at org.apache.ibatis.binding.MapperMethod$SqlCommand.(MapperMethod.java:232) ~[mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.binding.MapperMethod.(MapperMethod.java:50) ~[mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.binding.MapperProxy.lambda$cachedMapperMethod$0(MapperProxy.java:62) ~[mybatis-3.5.0.jar:3.5.0]
at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660) ~[na:1.8.0_101]
at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:62) ~[mybatis-3.5.0.jar:3.5.0]
.....
My mybatis config file is as follows (in src/main/resources):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- changes from the defaults -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- Mybatis logging -->
<setting name="logImpl" value="LOG4J2"/>
</settings>
<typeAliases>
<package name="com.qlsdistribution.fps.resolverender.data.mybatis.domain"/>
</typeAliases>
<mappers>
<mapper resource="mapper/ResolveJobReport.xml"/>
<!-- <mapper resource="com/qlsdistribution/fps/resolverender/data/mybatis/mapper/ResolveJobReport.xml"/> -->
</mappers>
</configuration>
As you can see I have tried different locations for the mapper xml file but if I put invalid syntax in the mapper xml file, it fails with invalid syntax (SAXParseException) instead so I know the mapper xml file is being read.
The mapper xml file is as follows (in src/main/resources/mapper):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qlsdistribution.fps.resolverender.data.mybatis.ResolveJobReportMapper">
<resultMap id="resolveJobReport" type="com.qlsdistribution.fps.resolverender.data.mybatis.domain.ResolveJobReport">
<result property="id" column="id" />
<result property="fpsProjectName" column="fps_project_name" />
<result property="inputPath" column="input_path" />
<result property="destinationPath" column="destination_path" />
<result property="presetName" column="preset_name" />
<result property="ipAddress" column="ip_address" />
<result property="frameRate" column="frame_rate" />
<result property="resolveProjectName" column="resolve_project_name" />
<result property="width" column="width" />
<result property="height" column="height" />
<result property="renderFormat" column="render_format" />
<result property="renderCodec" column="render_codec" />
<result property="scriptPath" column="script_path" />
<result property="cliOutput" column="cli_output" />
<result property="jobStartedDate" column="job_started_date" />
<result property="jobFinishedDate" column="job_finished_date" />
<result property="createdBy" column="created_by" />
<result property="createdDate" column="created_date" />
<result property="modifiedBy" column="modified_by" />
<result property="modifiedDate" column="modified_date" />
</resultMap>
<select id="getAllResolveJobReports" resultMap="resolveJobReport">
SELECT id, fps_project_name, input_path, destination_path, preset_name, ip_address, frame_rate, resolve_project_name, width, height,
render_format, render_codec, script_path, cli_output, job_started_date, job_finished_date, created_by, created_date, modified_by, modified_date
FROM resolve_job_report
WHERE fps_setting_id = #{value}
ORDER by id desc;
</select>
<select id="getAllResolveJobReportsById" parameterType="Long" resultMap="resolveJobReport">
SELECT id, fps_project_name, input_path, destination_path, preset_name, ip_address, frame_rate, resolve_project_name, width, height,
render_format, render_codec, script_path, cli_output, job_started_date, job_finished_date, created_by, created_date, modified_by, modified_date
FROM resolve_job_report
WHERE id = #{value};
</select>
<insert id="saveResolveJobReport" parameterType="com.qlsdistribution.fps.resolverender.data.mybatis.domain.ResolveJobReport">
INSERT INTO resolve_job_report
(fps_project_name, input_path, destination_path, preset_name, ip_address, frame_rate, resolve_project_name, width, height,
render_format, render_codec, script_path, cli_output, job_started_date, job_finished_date, created_by)
VALUE
(#{fpsProjectName},#{inputPath},#{destinationPath},#{presetName},#{ipAddress},#{frameRate},#{resolveProjectName},#{width},#{height},
#{renderFormat},#{renderCodec}, #{scriptPath},#{cliOutput},#{jobStartedDate},#{jobFinishedDate},#{createdBy});
</insert>
<update id="updateResolveJobReportById" parameterType="resolveJobReport">
UPDATE resolve_job_report
SET
fps_project_name = #{fpsProjectName},
input_path = #{inputPath},
destination_path = #{destinationPath},
preset_name = #{presetName},
ip_address = #{ipAddress},
frame_rate = #{frameRate},
resolve_project_name = #{resolveProjectName},
width = #{width},
height = #{height},
render_format = #{renderFormat},
render_codec = #{renderCodec},
script_path = #{scriptPath},
cli_output = #{cliOutput},
job_started_date = #{jobStartedDate},
job_finished_date = #{jobFinishedDate},
modified_by = #{modifiedBy}
where id = #{id};
</update>
<delete id="deleteResolveJobReporttById" parameterType="Long">
DELETE FROM resolve_job_report
WHERE id = #{value}
</delete>
</mapper>
My application.properties file contains the following (in (src/main/resources):
spring.datasource.url=jdbc:mysql://localhost:3306/fpsresolvetool?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.schema=classpath:schema.sql
mybatis.config-location=classpath:SqlMapConfig.xml
I have even tried using the latest mybatis versions in my pom.xml:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
My spring boot application is as follows:
#SpringBootApplication
#EnableScheduling
#ComponentScan({"com.qlsdistribution.fps.resolverender"})
#EnableJms
#MapperScan("com.qlsdistribution.fps.resolverender.data.mybatis")
public class FPSResolveRenderApp implements WebMvcConfigurer {
/** UTF-8 Character set name */
private static final String UTF_8 = "UTF-8";
/** Logger */
private static final Logger logger = LogManager.getLogger(FPSResolveRenderApp.class);
public static void main(String[] args) {
new SpringApplicationBuilder(FPSResolveRenderApp.class).run(args);
}
/**
* Creates and gets the FilterRegistrationBean
* #return
*/
#Bean
public FilterRegistrationBean<CharacterEncodingFilter> filterRegistrationBean() {
FilterRegistrationBean<CharacterEncodingFilter> registrationBean = new FilterRegistrationBean<CharacterEncodingFilter>();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding(UTF_8);
registrationBean.setFilter(characterEncodingFilter);
return registrationBean;
}
}
The mapper interface is as follows:
#Mapper
public interface ResolveJobReportMapper {
public List<ResolveJobReport> getAllResolveJobReports();
public List<ResolveJobReport> getAllResolveJobReports(RowBounds rowBounds);
public List<ResolveJobReport> getAllResolveJobReportsById(Long id);
public List<ResolveJobReport> getAllResolveJobReportsById(Long id, RowBounds rowBounds);
public void saveResolveJobReport(ResolveJobReport resolveJobReport);
public void updateResolveJobReportById(ResolveJobReport resolveJobReport);
public void deleteResolveJobReporttById(Long id);
}
And the service class is as follows:
#Service("ResolveJobReportService")
public class ResolveJobReportService {
#Autowired
private ResolveJobReportMapper resolveJobReportMapper= null;
public List<ResolveJobReport> getAllResolveJobReports() {
return resolveJobReportMapper.getAllResolveJobReports();
}
public List<ResolveJobReport> getAllResolveJobReports(RowBounds rowBounds) {
return resolveJobReportMapper.getAllResolveJobReports();
}
public List<ResolveJobReport> getAllResolveJobReportsById(Long id) {
return resolveJobReportMapper.getAllResolveJobReportsById(id);
}
public List<ResolveJobReport> getAllResolveJobReportsById(Long id, RowBounds rowBounds) {
return resolveJobReportMapper.getAllResolveJobReportsById(id);
}
public void saveResolveJobReport(ResolveJobReport resolveJobReport) {
resolveJobReportMapper.saveResolveJobReport(resolveJobReport);
}
public void updateResolveJobReportById(ResolveJobReport resolveJobReport) {
resolveJobReportMapper.updateResolveJobReportById(resolveJobReport);
}
public void deleteResolveJobReporttById(Long id) {
resolveJobReportMapper.deleteResolveJobReporttById(id);
}
}
Can anyone see what is wrong.
The problem happens because the namespace in mapper xml is com.qlsdistribution.fps.resolverender.data.mybatis.ResolveJobReportMapper but the package the mapper interface is com.qlsdistribution.fps.resolverender.data.mybatis.mapper.ResolveJobReportMapper.
To fix it make sure they match.
Put it in application.properties mybatis.mapper-locations=classpath*:**/mappers/*Mapper.xml
For those people using MyBatis without xml in spring boot project:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
Please check your spring boot application class, make sure your #MapperScan matches your dao package.
#MapperScan("com.jjs.videoservice.dao")
The path must be SAME as your dao package (contains your mapper interface), I ignored "dao" and caused the issue.
Hope it helps someone, thanks
I had the same error message when I changed my project from a JavaFX Project to a Maven Project.
I had to move all my xml mapper files to the resource folder. After that, worked just fine.
I hit this problem recenly, and checked everything that can be found in the internet. Cost me a whole day.
Finally I put the xml files in the same place with the interface java files, which solved the problem.
I think that is because for some reasons the xml files can not be found, and putting them there make them visiable.
I had the same issue
for me the fix was giving same filename for both the java (mapper interface class) and corresponding xml file
I had 2 mappers in the same package. It was the root cause of the problem. Once each mapper interface was moved to separate package, the problem was resolved.
in my case, I used the same name for mapper and java class but the mapping in mapper.xml was pointing to the wrong java class
I faced the same problem recently, I noticed, that I added the new method in the production xml mapper file by mistake and not in the actual xml mappers in resources folder. Once the actual xml mappers in resources folder was updated, it fixed the problem. So please make sure you update the right mapper files in your src folder that gets compiled.
Sometimes people do this mistake:
In resources folder the created folder like "org.my_app.mybatis", but the correct way is do separate folder for each part of package
-org
--my_app
---mybatis
It is hard to recognize when you do it in code editor.
Visually we have the same result
But actually a different structure
Green will work, red - won't.

Xamarin.Android: Unable to instantiate activity ComponentInfo

I am receiving this error when trying to launch a Xamarin forms application on Android from a text message URL. I have been following the steps noted in THIS article.
Here the application node in my AppManifest.xml
<application android:label="Label A">
<activity android:icon="#drawable/Icon" android:label="LabelB" android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="superduperapp" />
</intent-filter>
</activity>
</application>
According to the article I need to do something with intent objects to get the OnCreate override to fire but I think I am not matching something up right with my manifest and the naming convention for a class I created below.
[Activity(Label = "urlentryclass")]
public class OpenFromURI : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Intent outsideIntent = Intent;
var x = Intent.Data.EncodedAuthority;
}
}
So, with the above code added to my xamarin solution I also have a webpage with the code below..
and when i click the link above from my mobile browser it touches the mobile app because I get the error below
MyApp.Mobile.Droid.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "MyApp.Mobile.Droid.MainActivity" on path: DexPathList[[zip file "/data/app/MyApp.Mobile.Droid-1/base.apk"],nativeLibraryDirectories=[/data/app/MyApp.Mobile.Droid-1/lib/arm64, /data/app/MyApp.Mobile.Droid-1/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]] occurred
MyApp.Mobile.Droid.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "MyApp.Mobile.Droid.MainActivity"
Xamarin.Android, by default, generates the Java wrappers using MD5-based class names to avoid Java class name clashing, such as:
md579731053346ff64fcf21847b09163ce1.MainActivity
You have hard-coded a android:name=".MainActivity" in your manifest but the generated class will be MD5-based by default.
Open up your MainActivity and within the ActivityAttribute on your MainActvity class, add a fully qualified name within a Name parameter of that attribute, this will force the Xamarin.Android build process to use a Java-class name of your choosing vs. the MD5-based one and thus it will match your manifest entry.
Example:
[Activity(Name = "MyApp.Mobile.Droid.MainActivity", Label = "MySuperDuperApp", MainLauncher = true, Icon = "#mipmap/icon")]
public class MainActivity : Activity
{
~~~

Having trouble getting webapi selfhost working with ninject

I'm trying to get Ninject to work with a project that is using self a hosted WebApi connection.
I've installed the nuget package Microsoft ASP.NET Web API 2.2 Self Host (Microsoft.AspNet.WebApi.SelfHost) along with Ninject.Web.Common.Selfhost.
The console app seems to load up correctly, but I only seem to get a connection error when hitting my URL (http://localhost:8081/api/hello). I have a similar test app that is not using Ninject that works correctly.
I'm trying to follow this post: https://github.com/ninject/Ninject.Web.Common/wiki/Setting-up-a-self-hosted-web-application
Am I missing something to get this going? I originally tried using the package Microsoft.AspNet.WebApi.OwinSelfHost but could not get it functioning because of various errors. If this is what I need to be using, I can revisit this.
public class HelloController : ApiController
{
public string Get()
{
return "Hello, world!";
}
}
class Program
{
static void Main(string[] args)
{
var webApiConfiguration = new HttpSelfHostConfiguration("http://localhost:8081");
webApiConfiguration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
var mSelfHost = new NinjectSelfHostBootstrapper(CreateKernel, webApiConfiguration);
mSelfHost.Start();
Console.ReadLine();
}
private static IKernel CreateKernel()
{
var mKernel = new StandardKernel();
mKernel.Load(Assembly.GetExecutingAssembly());
return mKernel;
}
}
Here are the packages I have installed:
<packages>
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.SelfHost" version="5.2.2" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
<package id="Ninject" version="3.2.2.0" targetFramework="net45" />
<package id="Ninject.Web.Common" version="3.2.3.0" targetFramework="net45" />
<package id="Ninject.Web.Common.Selfhost" version="3.2.3.0" targetFramework="net45" />
</packages>
I was able to solve this by adding Ninject.Web.WebApi.SelfHost first. This loaded the appropriate WebApi packages automatically. Before I was loading the WebApi packages myself and then adding Ninject.

Sponsorship of remotely instanced objects

I have a singleton service on remote server, this has a method who returns new objects to clients:
public class MySingleton : MarshalByRefObject
{
public override object InitializeLifetimeService()
{
return null;
}
public MarshalByRefObject GetService()
{
return new Model();
}
}
public class Model : MarshalByRefObject
{
}
I don't want that Model instances live forever on server, so I just wanted to use the normal sponsorship procedure, on client side I create a sponsor for my Model, and I attach the remote lease to this sponsor:
var sponsor = new ClientSponsor();
_service = _mySingleton.GetService();
var success = sponsor.Register(_service);
Well, this does not work. The remote object Model, dies after a while.
Do you confirm this behavior ?
I guess it's because the lifetime manager on server doesn't have the opportunity to initialize the lease, because the object Model is instanced and returned directly.
I know this is an old post but during my search for an similar issue I stumbled on this post.
Maybe it will depend on the SinkProvider configuration. Because the Renewal call on Client side from server require an deserialization. In the app.exe.config on server side you have to setup the serverProvider and also the clientProvider like this:
<channel ref="tcp" port="50220" useIpAddress="false">
<serverProviders>
<formatter ref="binary" typeFilterLevel="Full" />
</serverProviders>
<clientProviders>
<formatter ref="binary" />
</clientProviders>
</channel>
<channel ref="http" port="50221" useIpAddress="false">
<serverProviders>
<formatter ref="soap" typeFilterLevel="Full" />
</serverProviders>
<clientProviders>
<formatter ref="soap" />
</clientProviders>
</channel>
On the client side use the following app.config.exe:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.runtime.remoting>
<application>
<channels>
<channel ref="tcp" port="0">
<serverProviders>
<formatter ref="binary" typeFilterLevel="Full"/>
</serverProviders>
</channel>
</channels>
</application>
</system.runtime.remoting>
</configuration>

Resources